Java try-catch

Java try block

The try block contains set of statements where an exception can occur. A try block is always followed by a catch block, which handles the exception that occurs in associated try block. A try block must be followed by catch blocks or finally block or both.

Syntax
try{ //statements that may cause an exception }

While writing a program, if you think that certain statements in a program can throw a exception, enclosed them in try block and handle that exception

Catch block

A catch block is where you handle the exceptions, this block must follow the try block. A single try block can have several catch blocks associated with it. You can catch different exceptions in different catch blocks. When an exception occurs in try block, the corresponding catch block that handles that particular exception executes. For example if an arithmetic exception occurs in try block then the statements enclosed in catch block for arithmetic exception executes.

Syntax
try { //statements that may cause an exception } catch (exception(type) e(object))‏ { //error handling code }
Example: try catch block

If an exception occurs in try block then the control of execution is passed to the corresponding catch block. A single try block can have multiple catch blocks associated with it, you should place the catch blocks in such a way that the generic exception handler catch block is at the last(see in the example below).

The generic exception handler can handle all the exceptions but you should place is at the end, if you place it at the before all the catch blocks then it will display the generic message. You always want to give the user a meaningful message for each type of exception rather then a generic message.

class Test { public static void main(String args[]) { int num1, num2; try { num1 = 0; num2 = 62 / num1; System.out.println(num2); System.out.println("Hey I'm at the end of try block"); } catch (ArithmeticException e) { /* This block will only execute if any Arithmetic exception * occurs in try block */ System.out.println("You should not divide a number by zero"); } catch (Exception e) { System.out.println("Exception occurred"); } System.out.println("I'm out of try-catch block in Java."); } }


Output:
You should not divide a number by zero I'm out of try-catch block in Java.
Multiple catch blocks in Java

The example we seen above is having multiple catch blocks, lets see few rules about multiple catch blocks with the help of examples. To read this in detail, see catching multiple exceptions in java.

  1. As I mentioned above, a single try block can have any number of catch blocks.

  2. A generic catch block can handle all the exceptions. Whether it is ArrayIndexOutOfBoundsException or ArithmeticException or NullPointerException or any other type of exception, this handles all of them. To see the examples of NullPointerException and ArrayIndexOutOfBoundsException, refer this article: Exception Handling example programs.

    catch(Exception e) { //This catch block catches all the exceptions }
    If you are wondering why we need other catch handlers when we have a generic that can handle all. This is because in generic exception handler you can display a message but you are not sure for which type of exception it may trigger so it will display the same message for all the exceptions and user may not be able to understand which exception occurred. Thats the reason you should place is at the end of all the specific exception catch blocks

  3. If no exception occurs in try block then the catch blocks are completely ignored.

  4. Corresponding catch blocks execute for that specific type of exception:
    catch(ArithmeticException e) is a catch block that can hanlde ArithmeticException
    catch(NullPointerException e) is a catch block that can handle NullPointerException

  5. You can also throw exception, which is an advanced topic and I have covered it in separate tutorials: user defined exception, throws keyword, throw vs throws.

class Test { public static void main(String args[]) { try{ int a[]=new int[7]; a[4]=30/0; System.out.println("First print statement in try block"); } catch(ArithmeticException e){ System.out.println("Warning: ArithmeticException"); } catch(ArrayIndexOutOfBoundsException e){ System.out.println("Warning: ArrayIndexOutOfBoundsException"); } catch(Exception e){ System.out.println("Warning: Some Other exception"); } System.out.println("Out of try-catch block..."); } }


Output:
Warning: ArithmeticException Out of try-catch block...

In the above example there are multiple catch blocks and these catch blocks executes sequentially when an exception occurs in try block. Which means if you put the last catch block ( catch(Exception e)) at the first place, just after try block then in case of any exception this block will execute as it can handle all exceptions. This catch block should be placed at the last to avoid such situations.

Problem without exception handling
public class Test { public static void main(String args[]) { int data=50/0; System.out.println("rest of the code..."); } }


Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero at Test.main(Test.java:5)

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
public class Test { 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:
java.lang.ArithmeticException: / by zero rest of the code...
Internal working of java try-catch block
internal working of 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.

Example of Control flow in try-catch:
// Java program to demonstrate // control flow of try-catch clause // when exception occur in try block // and handled in catch block class Test { 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"); } // rest program will be excuted System.out.println("Outside try-catch clause"); } }


Output:
Exception caught in Catch block Outside try-catch clause
Control flow in try-catch-finally clause :
// Java program to demonstrate // control flow of try-catch-finally clause // when exception occur in try block // and handled in catch block class Test { 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"); } }


Output:
Exception caught in catch block finally block executed Outside try-catch-finally clause
try-catch clause :
// Java program to demonstrate // control flow of try-catch clause // when exception occurs in try block // but not handled in catch block class Test { 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"); } // not a appropriate handler catch(NullPointerException ex) { System.out.println("Exception has been caught"); } // rest program will not execute System.out.println("Outside try-catch clause"); } }


Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4 at Test.main(Test.java:14)
try-catch-finally clause :
// Java program to demonstrate // control flow of try-catch-finally clause // when exception occur in try block // but not handled in catch block class Test { 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"); } // not a appropriate handler catch(NullPointerException ex) { System.out.println("Exception has been caught"); } finally { System.out.println("finally block executed"); } // rest program will not execute System.out.println("Outside try-catch-finally clause"); } }


Output:
finally block executed Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4 at Test.main(Test.java:15)
try-catch clause :
// Java program to demonstrate try-catch // when an exception doesn't occurred in try block class Test { public static void main (String[] args) { try { String str = "123"; int num = Integer.parseInt(str); // this statement will execute // as no any exception is raised by above statement System.out.println("Inside try block"); } catch(NumberFormatException ex) { System.out.println("catch block executed..."); } System.out.println("Outside try-catch clause"); } }


Output:
Inside try block Outside try-catch clause
try-catch-finally clause
// Java program to demonstrate try-catch-finally // when exception doesn't occurred in try block class Test { public static void main (String[] args) { try { String str = "123"; int num = Integer.parseInt(str); // this statement will execute // as no any exception is raised by above statement System.out.println("try block fully executed"); } catch(NumberFormatException ex) { System.out.println("catch block executed..."); } finally { System.out.println("finally block executed"); } System.out.println("Outside try-catch-finally clause"); } }


Output:
try block fully executed finally block executed Outside try-catch-finally clause
Control flow in try-finally

In this case, no matter whether an exception occur in try-block or not, finally will always be executed. But control flow will depend on whether exception has occurred in try block or not.

1.Exception raised: If exception has been occurred in try block then control flow will be finally block followed by default exception handling mechanism.

// Java program to demonstrate // control flow of try-finally clause // when exception occur in try block class Test { 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"); } finally { System.out.println("finally block executed"); } // rest program will not execute System.out.println("Outside try-finally clause"); } }


Output:
finally block executed Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4 at Test.main(Test.java:13)

1.Exception not raised: If exception is not occurred in try block then control flow will be finally block followed by rest of the program

// Java program to demonstrate // control flow of try-finally clause // when exception doesn't occur in try block class Test { public static void main (String[] args) { try { String str = "123"; int num = Integer.parseInt(str); // this statement will execute // as no any exception is raised by above statement System.out.println("Inside try block"); } finally { System.out.println("finally block executed"); } // rest program will be executed System.out.println("Outside try-finally clause"); } }


Output:
Inside try block finally block executed Outside try-finally clause
Finally block

I have covered this in a separate tutorial here: java finally block. For now you just need to know that this block executes whether an exception occurs or not. You should place those statements in finally blocks, that must execute whether exception occurs or not.




Instagram