Friday, April 2, 2021

try-catch Block in Java Exception Handling

In this post we'll see how exception handling can be done using try-catch block in Java.

try block in Java

try block is used to enclose the code that might throw an exception. try block must be followed by either catch or finally block or both.

General form of Java try block

try {
  code 
}
catch and/or finally blocks
 

catch Block in Java

catch block is used to handle the exception thrown with in a try block. There can't be any code between the end of the try block and the beginning of the first catch block.

General form of Java catch block

try {

} catch (ExceptionType name) {

} catch (ExceptionType name) {

}

If try-catch block is not used

Let's first see what happens if try-catch block is not used for exception handling in a Java code that throws an exception.

public class ExceptionDemo {
  public static void main(String[] args) {
    int a = 0;
    int b = 7 / a;
    System.out.println("After exception");
  }
}

In this program an attempt is made to divide by 0, which will result in an exceptional condition. When run time system detects that, it creates an Exception object and throws it. Since we are not providing any exception handling of our own exception propagation will happen and it will be caught by the default handler, provided by the Java run-time system.

Output

Exception in thread "main" java.lang.ArithmeticException: / by zero
 at org.netjs.examples.impl.ExceptionDemo.main(ExceptionDemo.java:7)

Note that the line "After exception" is not printed, as default handler automatically terminates the program if an exception occurs.

Using try catch block for exception handling

It is always good to provide exception handling of your own. As it helps to maintain the flow of the program and prevents the program from terminating automatically. It will definitely be very confusing for the users of a program if program stops running and prints a stack trace whenever an error occurred. Notice how it was automatically terminated in the above program where no exception handling was provided.
Using try-catch block prevents that from happening, let's see it with the same example.

public class ExceptionDemo {

 public static void main(String[] args) {
  try{
  int a = 0;
  int b = 7 / a;
  System.out.println("After exception");
  } catch (ArithmeticException aExp) { 
   System.out.println("Division by zero.");
   aExp.printStackTrace();
  }
  System.out.println("After catch statement.");
 }
}

Output

Division by zero.
java.lang.ArithmeticException: / by zero
 at org.netjs.examples.impl.ExceptionDemo.main(ExceptionDemo.java:11)
After catch statement.

Notice that the call to println() inside the try block is never executed. Once an exception is thrown, program control transfers out of the try block into the catch block. Once the catch statement has executed, program control continues with the next line in the program. That's why the line "After catch statement" is printed.

In exceptional handling a well-constructed try-catch should catch and resolve the exceptional condition and then continue on as if the error had never happened.

For example let's take list of values and let it throw the same division by zero exception for one of the item in the list, with a proper exception handling it should continue with the next item in the list, rather than terminating the program.

Java try-catch block example

public class ExceptionDemo {

 public static void main(String[] args) {
  int b = 0;
  List <Integer> numList = new ArrayList<Integer>();
  // Putting values in a list
  numList.add(2);
  numList.add(3);
  numList.add(0);// putting zero
  numList.add(6);
  numList.add(8);
  // looping the list and dividing 24 by each 
  // integer retrieved from the list
  for(Integer i: numList){
  try{
   System.out.println("Dividing by " + i);
   // Division by zero will throw exception
   b = 24 / i;
  }catch (ArithmeticException aExp) { 
     System.out.println("Division by zero.");
     // Setting value to zero in case
     // of exception
     b = 0;
     aExp.printStackTrace();
  } 
  System.out.println("Value of b " + b);
  } 
  System.out.println("After for loop");
 }

}

Output

Dividing by 2
Value of b 12
Dividing by 3
Value of b 8
Dividing by 0
Division by zero.
java.lang.ArithmeticException: / by zero
Value of b 0 at org.netjs.examples.impl.ExceptionDemo.main(ExceptionDemo.java:23)

Dividing by 6
Value of b 4
Dividing by 8
Value of b 3
After for loop

It can be seen how in case of division by zero an exception is thrown, which is caught in the catch block and a default value of 0 is given to b in that case. After that for loop goes on with the next element in the list as if nothing happened.

Points to note-

  • There are three exception handler components in Java- try, catch and finally blocks to write an exception handler.
  • try block code must be surrounded by curly braces.
  • If there is a catch block, it must immediately follow a try block.
  • finally block can also be used just after the try block in absence of a catch block.

That's all for this topic try-catch Block in Java Exception Handling. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Multiple Catch Blocks in Java Exception Handling
  2. Nested Try Statements in Java Exception Handling
  3. Difference Between throw And throws in Java
  4. Best Practices For Exception Handling in Java
  5. Java Exception Handling Interview Questions And Answers

You may also like-

  1. finalize() Method in Java
  2. static Reference to The Non-static Method or Field Error
  3. Java Abstract Class and Abstract Method
  4. Thread Priority in Java Multi-Threading
  5. Difference Between yield and sleep in Java Multi-Threading
  6. Functional Interfaces in Java
  7. equals() And hashCode() Methods in Java
  8. Java ArrayBlockingQueue With Examples

No comments:

Post a Comment