An unexpected event leads to abnormal termination of the application. To prevent that, we catch exceptions at certain points and handle the unexpected events there.
The root class for all errors and exceptions is Throwable. Inside of this, the root class of the exceptions is Exception. There can be many kind of exceptions but with the root one, we can catch all in one step. However, in this case, we can not differentiate between what kind of exception has been raised.
FIGURE OF THE HIERARCHY OF THE EXCEPCIONS:
In order to detect a possible exception, we use a try-catch, try-finally, try-catch-finally or try-with-resources statement.
In its try branch we put the sensitive expressions, statements which can result an exception.
In case there was none, the flow will continue with the finally block (if exists), closes the resources (if defined) and moves forward.
In case an exception was raised, the flow jumps into the proper catch block (if defined; in case it is not defined, the exception remains unhandled), process it, then if there is, follows in the finally block, closes resources if defined, then moves forward.
EXAMPLE FOR HANDLING EXCEPTION IN SCOPE:
Must be aware that in case in the catch and/or the finally branch an other exception can be raised, with nesting an other try statement, it must be handled that as well.
Intentionally, an exception can be raised by using the throw statement.
A raised exception must be handled, therefore should throw one from inside a try block.
EXAMPLE OF RAISING AN EXCEPTION:
In many cases it is better to prepare a method for throwing one or more exceptions so the caller scope can detect if there is any problems popping out while running the method. Most of the methods in Java libraries work in this way so the developer can decide upon integrating the method how to handle the error.
Following this structure is a decision by design.
Using this structure by the developer of the method means the developer that some operations can raise exception(s) but does not want (or can) handle it inside the scope of the method. In this case the caller method must handle the possible exception(s) by applying a try clause when calling the method.
EXAMPLE FOR MARKING THE POSSIBLE RAISED EXCEPCIONS IN METHOD SIGNATURE:
In case of using try-with-resources statement and in the resource declaration and in the try block exception is raised at the same time, the exception will be thrown from the try block but not from the resource declaration, the last one is suppressed.
To handle such problem, use the next formula.
EXAMPLE FOR HANDLING SUPRESSED EXCEPTION:
The next classes are used for the common raised exceptions when the developer wants to differenciate the cause of the raising error:
NullPointerException
IllegalArgumentException
ArrayIndexOutOfBoundsException
StringIndexOutOfBoundsExceptionÂ
NumberFormatExceptionÂ
ClassCastException
EXAMPLE FOR HANDLING PROBLEMS OF GIVEN ARGUMENTS UPON CALLING A METHOD: