Java Try Catch Block with Example

Java Try-Catch Block | In the previous tutorial, we have known that when an error occurs within a method of program, the method creates an exception object and hand over it to the runtime system (JVM).

The process of creating an exception object and handing it to runtime system is called throwing an exception in Java. This exception object contains information about exception name, type of exception, and state of the program where exception occurred.

After a method throws an exception, JVM searches for a method in the call stack that contains a block of code that handles the exception. This process is called catching an exception.

A block of code that catches the exception thrown by JVM is called exception handler. This whole mechanism is called exception handling in Java.

In Java, the basic concepts of exception handling are throwing an exception and catching it.

Five keywords to handle Exception in Java


Java provides five essential keywords to handle an exception. They are as:

  • try
  • catch
  • finally
  • throw
  • throws

These keywords can be used to handle exceptions properly. In this tutorial, we will know the first two keywords try and catch block with example programs. So, let’s proceed.

Try Block in Java


A keyword “try” is a block of code or statements that might throw an exception. That’s why a try block is also known as exception generated block.

The Java code that may generate an exception during the execution of program, must be placed within a try block. That is, we should place exception generated code (risky code) inside try block. We should not keep normal code inside try block.

Suppose there are three statements inside try block. First statement may occur exception and is on top inside try block. The other two statements are normal and are below the first statement.

If an exception occurred in statement 1, other two normal statements will not be executed. Therefore, the length of code inside the try block should be as much as less.

The three possible forms of try block are as follows:

  • try-catch: A try block is always followed by one or more catch blocks.
  • try-finally: A try block followed by a finally block.
  • try-catch-finally: A try block followed by one or more catch blocks followed by a finally block.

Catch Block in Java


A keyword “catch” is a block of code that handles the exception thrown by the try block. That’s why it is also known as exception handler block.

A catch block that catches an exception, must be followed by try block that generates an exception.

The general syntax of try-catch block (exception handling block) is as follows:

try 
{ 
  // A block of code; // generates an exception 
} 
catch(exception_class var) 
{ 
  // Code to be executed when an exception is thrown. 
}

In the above syntax, exception_class represents a type of exception class or subclass and var represents a variable name that refers to the exception stack where exception details are stored.

Exception Handling Mechanism using Try-Catch block


A systematic representation of relation between try and catch block in java is shown in the below figure.

Exception Handling Mechanism using Java Try Catch block

The try-catch block is a technique used to catch and handle the exception. If an exception occurs in the try block, the rest of code in try block is not executed and the control of execution is transferred from the try block to catch block that handles exception thrown by try block.


A catch block acts as an exception handler that takes a single argument. This argument is a reference of an exception object that can be either the same class exception or superclass exception.

If the catch block argument matches with the type of exception object thrown by try block, the exception is handled and statements in the catch block are executed.

But if catch argument is not matched, the exception is not caught and the default exception handler will terminate the program abnormally.

In case no exception is thrown by java try block then the catch block is ignored and the control of execution is passed to the next statement after the catch block.

Rules for using Try-Catch block in Java


There are some rules for using try-catch block in java program. They are as follows:

1. Java try-catch block must be within a method.

2. A try block can not be used without a catch or finally block. It must be followed by at least one catch block otherwise, the compilation error will occur.

3. A catch block must be followed by try block. There should not be any statement between the end of try block and the beginning of catch block.

4. A finally block cannot come before catch block.

Control Flow of Try Catch Block


Let’s understand the control flow inside the try-catch block with a suitable example. Consider the below code.

try 
{ 
  statement 1; 
  statement 2; 
  statement 3; 
} 
catch(exception_class var) 
{ 
  statement 4; 
} 
statement 5;

In the above code, there are three statements inside try block, one statement block inside catch block, and one statement outside try-catch block. Let’s see different cases.

Case 1:

Suppose no exception occurs inside try block, then statement 1, statement 2, and statement 3 will be executed normally. But, the catch block will not be executed because no exception is thrown by try block.

After complete execution of try block, the control of execution will be passed to the next statement. Now, statement 5 will execute normally. Thus, the control flow will be like this:

statement 1 ➞ statement 2 ➞ statement 3 ➞ statement 5 ➞ normal termination of program.

If no exception occurs within try block, Except catch block, all remaining code will be executed normally.

Case 2:

Suppose an exception occurs in statement 2 inside try block and the exception object created inside try block is matched with argument of catch block. What will be the control flow in this case?

a. Inside try block, statement 1 will be executed normally.

b. When the exception occurred in statement 2, the control of execution immediately is transferred to catch block and statement 4 inside the catch block will be executed.

c. After executing statement 4, statement 3 in try block will not be executed because the control never goes back to execute remaining code inside try block.
Control Flow of Try Catch Block in Java

d. After complete execution of catch block, statement 5 will be executed normally. Thus, the control flow will be like this:

statement 1 ➞ statement 4 ➞ statement 5 ➞ normal termination.

Case 3:

Suppose an exception occurred at statement 2 and exception object created is not matched with argument of the catch block. In this case, what will be the control flow?


a. Statement 1 will be executed normally within try block.

b. If an exception occurred in statement 2 and the exception object created does not match with argument of catch block, program will be terminated abnormally and the rest of code will not execute.

For example, suppose an exception object is created for ArithmeticException class and catch block has a reference of NullPointerException exception object as an argument, in this case, both are not matched and program will be terminated abnormally. So, the control flow will be like this:

statement 1 ➞ abnormal termination.

Case 4:

Suppose an exception occurred in statement 4 inside the catch block. In this case, what will be control flow?

Note that an exception occurs not only inside try block but also can occur inside catch and finally block. Since the exception has occurred in statement 4 inside catch block and statement 4 is not inside the try block, the program will be terminated normally.

Thus, control flow is like this:

statement 1 ➞ statement 2 ➞ statement 3 ➞ statement 5 ➞ normal termination.

If an exception occurs in any statement and statement is not inside the try block, the program will be terminated normally.

Case 5:

Suppose an exception occurs in statement 5. In this case, what will be control flow?

Since statement 5 is not inside try block, program will be terminated abnormally. The control flow will be as follows:

statement 1 ➞ statement 2 ➞ statement 3 ➞ abnormal termination.

Exception Handling using Try-catch block


Let’s take a simple example program where we will perform some illegal operations like division by zero without using java try-catch block.

Program code 1:

public class TryCatchEx {
public static void main(String[] args) 
{ 
   System.out.println("11"); 
   System.out.println("Before divide"); 
   int x = 1/0; // Exception occurred.
   System.out.println("After divide"); 
   System.out.println("22"); 
 } 
}
Output: 
       11 
       Before divide 
       Exception in thread "main" java.lang.ArithmeticException: / by zero

As you can see in the above example, the rest of the code is not executed and the program is terminated abnormally due to the generation of ArithmeticException at line int x = 1/0;.


Suppose if 100 lines of code are in the program after exception, then all the code after exception will not be executed. To overcome this situation, we will use Java try-catch block. So, let’s see how?

Program code 2:

public class TryCatchEx1 {
public static void main(String[] args) 
{ 
   System.out.println("11"); 
   System.out.println("Before divide"); 

// Applying try-catch block to handle exception.
   try 
   { 
     int x = 1/0; 
     System.out.println("After divide"); 
   } 
   catch(ArithmeticException ae) // Here, ae is a reference variable of exception object. 
   { 
     System.out.println("A number cannot be divided by zero"); 
   } 
   System.out.println("22"); 
 } 
}
Output: 
       11 
       Before divide 
       A number cannot be divided by zero 
       22

As you can see in the above code, the exception is handled properly using try-catch block, and the rest of code is also executed.

Advanced Example Programs on Try-catch block


Let’s take some advanced example programs based on exception handling using Java try-catch block with a brief explanation.

Program code 3:

public class TryCatchEx2 {
public static void main(String[] args) 
{ 
 System.out.println("111"); 
 try 
 { 
   int x = 12/0; // exception occurred.
   System.out.println("Result of x: " +x);  
   System.out.println("333"); 
 } 
 catch(ArithmeticException ae) 
 { 
   System.out.println("Hello world"); 
 } 
 System.out.println("444"); 
 } 
}
Output: 
       111 
       Hello world 
       444

In the preceding code, an exception occurred in the first line inside try block. Since the exception object created is matched with argument of catch block, the control immediately is passed to the catch block without executing the rest of code inside try block. Inside the catch block, statement is executed normally.

Program code 4:

public class TryCatchEx3 {
public static void main(String[] args) 
{ 
 int x = 100, y = 0; 
 try 
 { 
   System.out.println("111"); 
   int z = x/y; 
   System.out.println("Result of z: " +z); 
 } 
 catch(ArithmeticException ae) 
 { 
   System.out.println("Hello Java"); 
 } 
 System.out.println("333"); 
 } 
}
Output: 
       111 
       Hello Java 
       333

Program code 5:

public class TryCatchEx4 
{ 
 int x = 30, y = 0; 
 void divide() 
 { 
  System.out.println("I am in method"); 
  try 
  { 
    System.out.println("I am in try block"); 
    int z = x/y; 
    System.out.println("Result of z: " +z); 
  } 
  catch(NullPointerException np) 
  { 
    System.out.println("I am in catch block"); 
  } 
}
public static void main(String[] args) 
{ 
 TryCatchEx4 obj = new TryCatchEx4(); 
 System.out.println("I am in main method"); 
  obj.divide(); 
 } 
}
Output: 
       I am in main method 
       I am in method 
       I am in try block 
       Exception in thread "main" java.lang.ArithmeticException: / by zero

In the above code, an exception object created in try block does not match with argument of catch block. Therefore, exception is not handled by catch block, and the program is terminated abnormally.

Program code 6:

public class TryCatchEx5 {
public static void main(String[] args) 
{ 
 try 
 { 
   System.out.println("111"); 
   System.out.println("222"); 
 } 
 catch(ArithmeticException ae) 
 { 
   System.out.println("333"); 
 } 
 System.out.println("444"); 
 } 
}
Output: 
      111 
      222 
      444

In this example, no exception occurred in the try block. Therefore, the control of execution will not transfer to the catch block to execute the statement.

Program code 7:

public class TryCatchEx6 {
public static void main(String[] args) 
{ 
 System.out.println("111"); 
 try 
 { 
   System.out.println("222"); 
   int y = 1/0; 
 } 
 catch(ArithmeticException e) 
 { 
  try 
  { 
    System.out.println("Hello"); 
    int x = 20/0; 
  } 
  catch(NullPointerException np) 
  { 
     System.out.println("333"); 
  } 
 } 
 System.out.println("444"); 
 } 
}
Output: 
       111 
       222 
       Hello 
       Exception in thread "main" java.lang.ArithmeticException: / by zero

In this example, an exception occurred inside the try block of catch block has not handled. This is because NullPointerException does not handle the arithmetic exception.

Program code 8:

public class TryCatchEx7 {
public static void main(String[] args) 
{ 
 try 
 { 
    int a[] = {20, 30, 40, 50}; 
    a[10] = 5; 
 } 
 catch(ArrayIndexOutOfBoundsException a) 
 { 
    System.out.println("Array Index Out Of Bounds Exception"); 
  } 
 } 
}
Output: 
       Array Index Out Of Bounds Exception

Program code 9:

public class TryCatchEx8 {
public static void main(String[] args) 
{ 
 try 
 { 
// This method returns the Class object associated with the class or interface with the given string name.
   Class c = Class.forName("ArithmeticException"); 
 } 
 catch(ClassNotFoundException cn) 
 { 
    System.out.println(cn.getMessage()); 
  } 
 } 
}
Output: 
       ArithmeticException

In this example, the catch block has handled the exception occurred inside try block properly.

Program code 10:

public class TryCatchEx9 {
public static void main(String[] args) 
{ 
 try 
 { 
   String input = "Scientech Easy"; 
   int a = Integer.parseInt(input); 
   System.out.println("Value of a: " +a); 
 } 
 catch(NumberFormatException n) 
 { 
   System.out.println(n.getMessage()+ " is not an integer."); 
 }  
} }
Output: 
       For input string: "Scientech Easy" is not an integer.

Key Points to Remember:

1. An exception can be handled using try, catch, and finally blocks.

2. We can handle multiple exceptions using multiple catch blocks.

3. There can be a possibility for several exceptions inside the try block but at a time only one exception will be raised.

4. A single try block in Java can be followed by several catch blocks.

5. A catch block cannot be without try block but a try block can have without catch block.

6. We cannot write any statement between try and catch blocks.

7. We can also write a try block within another try block that is called nested try blocks.


Hope this tutorial has covered almost all important points related to try-catch block in java with example programs. I hope that you will have understood how to handle exception using Java try-catch block.

If you find anything incorrect in this tutorial, please inform us through email. Your email will be precious to us.
Thanks for reading!!!

⇐ PrevNext ⇒

Please share your love