January 11, 2024

Java try-catch Block With Examples

Robust code should be able to handle exceptional conditions too. In Java exception handling try and catch blocks are used to handle exceptions which helps in continuing with the flow of the program and also prevents the program from terminating automatically. In this post we'll see details about try-catch block in Java.

Try block in Java

If code in your method throws an exception, the default exception handling mechanism will stop your method execution and throw that exception to be handled by default handler. If you want to capture that exception with in the method then you should enclose your code, that might throw an exception, in try block.

General form of try block in Java is as follows-
try{
  ....
  ....
}
catch and finally blocks.

Try block must be followed by a catch block or a finally block or both. There can be multiple catch blocks too after try block.

Catch block in Java

A catch block is used to handle the exception thrown in the try block. A catch block must immediately follow a try block. There can be multiple catch blocks for different exception types that can be thrown in a try block.

See how you can handle different exceptions with in one catch block using Multi-Catch Exception in Java.

A try-catch-finally block in Java has the following form-

try {
   // Code that may throw excpetion
}
catch (ExceptionType1 exp){
   // Exception handler for  ExceptionType1
}
catch(ExceptionType2 exp){
  // Exception handler for  ExceptionType2
}
finally{
  // code that has to be executed after try block completes
}

If try-catch not used to handle exceptions

First let’s see what happens when you don’t use try-catch block in Java for handling exception in your code. Here we have a method which takes 2 integer as arguments and divide those numbers. In the code divisor is passed as zero, which will result in ArithmeticException.

public class ExceptionDemo {
  public static void main(String[] args) {
    ExceptionDemo ed = new ExceptionDemo();
    double result = ed.division(7, 0);
    System.out.println("result is - " + result);
  }

  private double division(int num1, int num2){
    double result;
    result = num1/num2;
    
    return result;	
  }
}
Output
Exception in thread "main" java.lang.ArithmeticException: / by zero
at com.knpcode.ExceptionDemo.division(ExceptionDemo.java:13)
at com.knpcode.ExceptionDemo.main(ExceptionDemo.java:7)

Since there is no try-catch block in the code, default exception handler is called in case of exception which terminates the program and prints the stack trace.

Using try-catch block for exception handling

You can write the same code with a try-catch block in Java where you handle the exceptional condition in your code and pass the result as zero in case of exception along with an appropriate message.

public class ExceptionDemo {
  public static void main(String[] args) {
    ExceptionDemo ed = new ExceptionDemo();
    double result = ed.division(7, 0);
    System.out.println("result is - " + result);
  }
	
  private double division(int num1, int num2){
    double result;
    try{
      result = num1/num2;
    }catch(ArithmeticException exp){
      System.out.println("Exception occurred while dividing" + exp.getMessage());
      // assigining zero to result
      result = 0;
    }
    return result;	
  }
}
Output
Exception occurred while dividing/ by zero
result is - 0.0
In this changed code you can see that program is not terminated when the exception occurred, result value is displayed now. In the catch block exception is handled by assigning zero to result and also message is displayed showing the cause of exception.

Nested try statement in Java

You can have a nested try statement also in Java exception handling. In a nested try a try-catch block resides with in an outer try-catch block. Once code enters a nested try statement that becomes the current context for exception handling. In case an exception occurs in an inner try and no catch block is found to handle the exception of that type, next (outer) try statement is checked for an exception handler and so on.

General form of nested try statement in Java

 
try{
  ..
  ..
  try{
	..
	..
  }catch(ExceptionType-1 e){
	..
	..
  }
}catch(ExceptionType-2 e){
	..
	..
}

Advantages of Nested try statement

If you have a section of code that may throw a specific exception then you can enclose that section with in a try-catch block to handle that exception. Outer most try statement which encloses the whole code may be designed to catch more generic exceptions.

Java nested try statement example

Here we have a Java program where two arguments are passed and then one passed argument is divided by another. So we can check for number of arguments and throw an illegal argument exception that should be caught by the outermost handler. While dividing check for division by zero exception which should be handled by a nested try statement. While converting passed arguments to int you can check for NumberFormatException with in a nested try statement.

public class NestedTryDemo {
  public static void main(String[] args) {
    int num1 = 0;
    int num2 = 0;
    try{
      if(args.length != 2){
        throw new IllegalArgumentException("Two parameters should be passed");
      }
      try{
        num1 = Integer.parseInt(args[0]);
        num2 = Integer.parseInt(args[1]);
        System.out.println("num1 = " + num1 + "num2 = " + num2);
      }catch(NumberFormatException e){
        System.out.println("Error while converting string to integer");
        throw e;
      }
      try{
        double result = num1/num2;
      }catch(ArithmeticException e){
        System.out.println("Error while division");
        e.printStackTrace();
      }
      
    }catch(Exception exp){
      exp.printStackTrace();
    }
  }
}

Trying to run this code with arguments "2" and "t5" will result in following exception.

java.lang.NumberFormatException: For input string: "t5"
	at java.lang.NumberFormatException.forInputString(Unknown Source)
	at java.lang.Integer.parseInt(Unknown Source)
	at java.lang.Integer.parseInt(Unknown Source)
	at com.knpcode.NestedTryDemo.main(NestedTryDemo.java:14)

Trying to run this code with arguments "3" and "0" will result in following exception.

num1 = 3num2 = 0
Error while division
java.lang.ArithmeticException: / by zero
	at com.knpcode.NestedTryDemo.main(NestedTryDemo.java:21)
Important points-
  • Code that may throw an exception should be enclosed with in a try block.
  • To associate an exception handler with a try block, you must put a catch block after it.
  • No code can be between the end of the try block and the beginning of the first catch block.
  • You can also have a finally block after a try-catch block or after a try block.

That's all for the topic Java try-catch Block With Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment