Exception handling in Java is made possible through the use of some keywords like try, catch, throw, throws, and finally. These keywords are used to manage how exceptions are thrown and handled.
Any piece of code that might cause an exception to be thrown is written in a try block. Code that might throw an exception usually deal with input values, which are not guaranteed to always be the way the programmer wants.
Imagine a baby that tries to walk. You simply put your hands around the baby to ensure that the baby does not fall and injure themselves. In the same way, the try block is used to surround code that might throw an exception while running.
A try block is followed immediately by a catch block or a finally block or both.
A catch block does exactly what its name says: it catches an exception thrown in the try block. Since a number of exceptions can be thrown, the catch block must specify the class of exception it is handling.
Beyond a catch block, there is the finally block, which simply works when the try block is done. So, the finally block waits for the try block to execute. Note that a try block can be followed by a catch block or a finally block or a combination of both. If the try block has a catch block, finally runs after the catch, otherwise the finally block runs immediately after the try block.
So imagine the finally block as the final resort for a try block. The finally block is normally used for handling resources that might not have been properly utilized by the try block.
A method, or a piece of code that performs a specific function in Java, can throw a type of exception by using the throws keyword in the method heading.
Exceptions in the Error or RuntimeException and their subclasses need not be included in the throws statement. They are classified as Unchecked Exceptions, which are exceptions that should be prevented in any way possible and must not be consciously allowed to occur.
The number of Unchecked Exceptions that can occur in a program are so enormous that we cannot throw all the Unchecked Exceptions in a method. It would cause the method to lose its clarity, so Java assumes that a programmer running a program does not intentionally throw these type of exceptions.
Every method is already liable of throwing unchecked exceptions when something goes wrong, so no need to add unchecked exceptions in the throws statement.
The throw keyword is used to specifically throw an exception in a method. It simply serves the normal use as in the verb throw: it throws an object of the Throwable Class. You cannot throw objects that are not in the Throwable Class or any of its subclasses. Be careful to not throw Unchecked Exceptions with the throw keyword. Use the throw keyword for throwing Checked Exceptions.
Recommended Posts