Java Exceptions
In this tutorial, we will learn about exceptions in Java. We will cover errors, exceptions and different types of exceptions in Java.
An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally, which is not recommended, therefore, these exceptions are to be handled.
Following are some scenarios where an exception occurs.
- A user has entered an invalid data.
- A file that needs to be opened cannot be found.
- A network connection has been lost in the middle of communications or the JVM has run out of memory.
Java Exception hierarchy
Here is a simplified diagram of the exception hierarchy in Java.
ExceptionHierarchy
Error: An Error indicates serious problem that a reasonable application should not try to catch.
Exception: Exception indicates conditions that a reasonable application might try to catch.
Java Exception Types
The exception hierarchy also has two branches: RuntimeException and IOException.
- 1. RuntimeException
RuntimeException is the superclass of those exceptions that can be thrown during the normal operation of the Java Virtual Machine. RuntimeException and its subclasses are unchecked exceptions.
You can think about it in this way. “If it is a runtime exception, it is your fault”.
The Runtime Exception usually shows the programmer's error, rather than the condition a program is expected to deal with. Runtime Exceptions are also used when a condition that can't happen. It should be noted that when a program is running out of memory, a program error is thrown instead of showing it as a Runtime Exception.
- 2. IOException
An IOException is also known as a checked exception. They are checked by the compiler at the compile-time and the programmer is prompted to handle these exceptions.
It can throw an IOException when the either the stream itself is corrupted or some error occurred during reading the data i.e. Security Exceptions, Permission Denied etc and/or a set of Exceptions which are derived from IOEXception