Exception is an unusual exceptional event describing an error, which occurs only during the compile-time or runtime of a Java program.
When an exception occurs, it is said to be thrown by the Java interpreter, which is responsible for the
execution of a Java program.
If this thrown exception is not handled in the program,
it stops the normal execution of the program and it ends abruptly.
That's why we should handle an exception when it is thrown by the program. This process of handing the exception is called Exception Handling.
Some factors due to which an exception may arise during the execution of a program -:
1) When we are trying to open a file that doesn't exist, such attempt will raise an exception.
2) When an integer number is divided by zero, it raises an exception.
3) When we try to access an array with an invalid index value, an exception is thrown.
Types of Exception -:
Java Exceptions are divided into two categories, depending on the time when the exceptions are checked.
1) Checked Exceptions This is a group of exceptions which are checked during the compile time of a program.
Checked exceptions are checked by the Java Compiler. Checked Exceptions extends the Exception class.
2) Unchecked Exceptions This is a group of exceptions which are only checked at the runtime of a program. Unchecked Exceptions are named so
because they are left unchecked at the compile time of a program by Java Compiler.
Unchecked exceptions are a type of RuntimeException class. Hence, unchecked exceptions are also called Runtime Exceptions.
RuntimeException class extends Exceptions class.
As you can see in the diagram above, both unchecked and checked exceptions are subtypes of Exception class.
The Exception class is a subclass of a class Throwable and Throwable class is itself a subclass of mother of all Java classes, Object.
What happens when an exception is thrown?
Exceptions are thrown at the runtime of a program. If an exception thrown during the runtime of a program is not handled within the program,
the program terminates right away without continuing any further.
Let us understand this by an example here.
Looking at the diagram above, it is easy to understand that if an exception is thrown when statement2 is executed, the program ends abruptly without executing any statement after it.
Hence, statement3 and statement4 will not be executed as a result of an exception at statement2.
In the next few pages, we will discuss Checked and Unchecked Exceptions and their various types.