Try Catch

Try Catch block is the first line of defense in handling an exception. If an exception has to be handled at the same point in code, and never to throw it to the calling method, try block is used.

How to use “try catch” ?

  • Enclose the code, which could possibly throw an exception, in the try block.
  • Follow the try block with catch blocks.
  • If an exception occurs, then runtime creates an exception object and finds the first suitable catch block.

The scenario mentioned is created in the following example, TryCatchDemo.java. In this example, there are two catch blocks following try block. Based on the type of exception object created, respective catch block is handed over the exception object. Looking at the code in the example, it is obvious that an ArithmeticException would be thrown. So, the catch block that handles ArithmeticException receives the exception object.

If another type of exception happens, runtime checks for a catch block that handles the specific exception. Incase not found, as java.lang.Exception is Super-class of exception classes in java.lang, it checks for the catch block that handles java.lang.Exception. If no catch block can handle an exception, it is thrown to the calling method.

Example.java

package com.tutorialkart.java;

public class Example {

	public static void main(String[] args) {
		new TryCatchDemo().routine();
		System.out.println("End of main");
	}

	public void routine(){
		System.out.println("In routine..");
		try {
			int c = 4/0;
			System.out.println("This statement is not printed if an exception occurs at the line above.");
		} catch (ArithmeticException e) {
			System.out.println("Exception is handled in ArithmeticException catch block.");
		} catch (Exception e) {
			System.out.println("Exception is handled in Exception catch block");
		}
		System.out.println("Continuing with rest of statements after try-catch block.");
	}
}

When the program is run, the output to console is

In routine..
Exception is handled in ArithmeticException catch block.
Continuing with rest of statements after try-catch block.Else
End of main

The path of the execution follows the yellow line starting from first statement in main() method, shown in the following figure:

ADVERTISEMENT
Path of execution with try catch block - Tutorialkart

Conclusion

In this Java Tutorial, we learnt the use of try catch block in Java to handle exceptions. In our next topic of Java tutorials, we shall learn how to Try with Resource.