try { //Protected code }catch(ExceptionName e1) { //Catch block }
Exception Handling in Java
It is a powerful feature provided in Java. It is a mechanism to handle run-time errors, so that the normal flow of the program is maintained.
Exception handling consists of the following five keywords:
- Try
- Catch
- Finally
- Throw
- Throws
try block
Enclose the code that might throw an exception in try block. It must be used within the method and must be followed by either catch or finally block.
Syntax of try with catch block
try{ ... }catch(Exception_class_Name reference){}
Syntax of try with finally block
try{ ... }finally{}
catch block
Catch block is used to handle the Exception. It must be used after the try block.
Code without exception handling:
class App{ public static void main(String args[]){ int index = 10/0; System.out.println("another code here"); } }
As displayed in the above example, rest of the code is not executed i.e. another code here statement is not printed. Let’s see what happens behind the scene:
The JVM firstly checks whether the exception is handled or not. If exception is not handled, JVM provides a default exception handler that performs the following tasks:
- Prints out exception description.
- Prints the stack trace (Hierarchy of methods where the exception occurred).
- Causes the program to terminate.
But if exception is handled by the application programmer, normal flow of the application is maintained i.e. rest of the code is executed.
Code with exception handling:
class App{ public static void main(String args[]){ try{ int index = 10/0; }catch(ArithmeticException e){ System.out.println(e); } System.out.println("another code here"); } }
Now, as displayed in the above example, rest of the code is executed i.e. another code here. statement is printed.