In this java programming tutorial post, we will study and understand the working of try, catch and finally block which helps in performing exception handling in java. Before we start of with this topic, you can checkout the Part 1 of Exception handling where we discussed the overall concept of Exception handling and how it works in Java. Click here to go the article.
Java Exception Handling Keywords –
There are 5 keywords used in java exception handling.
- try
- catch
- finally
- throw (we will study about this in other article)
- throws (we will study about this in other article)
Java try block
Java try block is used to enclose the code that might throw an exception. It must be used within the method. Java try block must be followed by either catch or finally block or both..
Syntax of java try-catch block
try{ //code that may throw exception }catch(Exception_class_Name ref){ }
Syntax of try-finally block
try{ //code that may throw exception }finally{}
Java catch block
Java catch block is used to handle the Exception. It must be used after the try block only. You can use multiple catch block with a single try.
Java finally block
Java finally block is a block that is used to execute important code such as closing connection, stream etc. Java finally block is always executed whether exception is handled or not. Java finally block follows try or catch block.
Problem without exception handling
Let’s try to understand the problem if we don’t use try-catch block.
public class Testtrycatch1{ public static void main(String args[]){ int data=50/0;//may throw exception System.out.println("rest of the code..."); } }
Output –
Exception in thread main java.lang.ArithmeticException:/ by zero
As displayed in the above example, rest of the code is not executed (in such case, rest of the code… statement is not printed). There can be 100 lines of code after exception. So all the code after exception will not be executed.
Solution by exception handling
Let’s see the solution of above problem by java try-catch block.
public class Testtrycatch2{ public static void main(String args[]){ try{ int data=50/0; }catch(ArithmeticException e){System.out.println(e);} System.out.println("rest of the code..."); } }
Output –
Exception in thread main java.lang.ArithmeticException:/ by zero rest of the code...
Now, as displayed in the above example, rest of the code is executed i.e. rest of the code… statement is printed.
Internal working of java try-catch block
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.
Program Example of Try Catch & Finally in Java –
// Java program to demonstrate // control flow of try-catch-finally clause // when exception occur in try block // and handled in catch block class TryCatchFinallyExample { public static void main (String[] args) { // array of size 4. int[] arr = new int[4]; try { int i = arr[4]; // this statement will never execute // as exception is raised by above statement System.out.println("Inside try block"); } catch(ArrayIndexOutOfBoundsException ex) { System.out.println("Exception caught in catch block"); } finally { System.out.println("finally block executed"); } // rest program will be executed System.out.println("Outside try-catch-finally clause"); } }
finally block executed
Outside try-catch-finally clause
Java Multi catch block
If you have to perform different tasks at the occurrence of different Exceptions, use java multi catch block. Let’s see a simple example of java multi-catch block.
public class TestMultipleCatchBlock{ public static void main(String args[]){ try{ int a[]=new int[5]; a[5]=30/0; } catch(ArithmeticException e){System.out.println("task1 is completed");} catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");} catch(Exception e){System.out.println("common task completed");} System.out.println("rest of the code..."); } }
rest of the code…
All catch blocks must be ordered from most specific to most general i.e. catch for ArithmeticException must come before catch for Exception.
Some Important points to remember –
- If you don’t handle exception, before terminating the program, JVM executes finally block(if any).
- For each try block there can be zero or more catch blocks, but only one finally block.
- At a time only one Exception is occurred and at a time only one catch block is executed.
- All catch blocks must be ordered from most specific to most general i.e. catch for ArithmeticException must come before catch for Exception.