How to handle exceptions using try-catch block?
An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. When an abnormal situation occurs within a method, an
Exception object is thrown. This object contains information about the error or unusual problems that occur.
Creating an exception object and handing it to the runtime system is called throwing an exception.
If you want to deal with the exceptions where they occur, you can include three kinds of code blocks in a method to handle them.
try block encloses code that may give rise to one or more exceptions
catch block encloses code that is intended to handle exceptions of a particular type that may be thrown in the associated try block
- The code in a
finally block is always executed before the method ends, regardless of whether any exceptions are thrown in the try block.
Here is what happening when we run the program:
java.lang.ArithmeticException: / by zero
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
Finally block is always executed.