Java Try Catch Block with Example

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, the basic concepts of exception handling are throwing an exception and catching it.

Hence, Java provides five essential keywords to handle an exception. They are: try, catch, finally, throw, and 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 program. 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 exception occurred in statement 1, other two normal statements will not be executed. Therefore, the length of code inside try block should be as much as less.


The three possible forms of try block are as follows:
1. try-catch: A try block is always followed by one or more catch blocks.
2. try-finally: A try block followed by a finally block.  
3. 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:
Syntax:

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 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 of using Try and 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 end of try block and beginning of catch block.
4. A finally block cannot come before catch block.

Control Flow of Try Catch Block in Java


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 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 abnormally. Thus, control flow is like this:
      statement 1  statement 2  statement 3  statement 4  Normal Termination.

👉 If an exception occurs in any statement and statement is not inside the try block then program will be terminated abnormally.

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.

Java Exception Handling Example Program


Let’s create a small java program where we will perform some illegal operation like division by zero without using java try-catch block.
Program source code 1:

public class TryCatchEx 
{
public static void main(String[] args) 
{ 
 System.out.println("11"); 
 System.out.println("Before divide"); 
 int x = 1/0; 
 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 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 source code 2:

public class TryCatchEx1 
{
public static void main(String[] args) 
{ 
  System.out.println("11"); 
  System.out.println("Before divide"); 
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, exception is handled properly using try-catch block and rest of code is also executed.

Now, let’s see different kind of example programs based exception handling using try-catch block with a brief explanation.

Program source code 3:

public class TryCatchEx2 
{
public static void main(String[] args) 
{ 
 System.out.println("111"); 
try 
{ 
  int x = 12/0; 
  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, exception occurred in first line inside try block. Since exception object created is matched with argument of catch block, the control immediately is passed to catch block without executing the rest of code inside try block. Inside catch block, statement is executed normally.

Program source 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 source 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, 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 source 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

Program source 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

Program source 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 source code 9:

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

Program source 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.

Final words
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?
Thanks for reading!!!
Next ⇒ Multiple Catch block in Java⇐ PrevNext ⇒

Leave a Comment