Try-Catch Block

Basic Structure:

  • The try-catch block is used to handle exceptions. The code that might throw an exception is placed inside the try block, and the catch block is used to handle the exception.

    try {
        // Code that might throw an exception
    } catch (ExceptionType e) {
        // Code to handle the exception
    }
With try-catch block
Output
Cannot divide by zero.
Without try-catch block
Output
Exception in thread "main" java.lang.ArithmeticException: / by zero
	at Example2.main(Example2.java:7)

Control Flow In Try-Catch Block

try {
	stmt-1;
	stmt-2;
	stmt-3;
} catch(Exception e) {
	stmt-4;
}
stmt-5;
  • If there is no Exception stmt-1, stmt-2, stmt-3, stmt-5 executed normally i.e Normal Termination.
  • If an Exception is raised at stmt-2 and corresponding catch block is matched then the flow of execution is stmt-1, stmt-4, stmt-5 executed normally i.e Normal Termination.
  • If an Exception is raised at stmt-2 and corresponding catch block is not matched then the flow of execution is, only stmt-1 executed and the program terminates abnormally i.e Abnormal Termination.
  • If an Exception is raised at stmt-4 (or) at stmt-5 then it is always an abnormal termination.