Tuesday, 19 May 2015

try-catch block in Java exception handling

try block

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

General form of try block

try {
    code 
}
catch and/or finally blocks
 

catch Block

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 catch block

try {

} catch (ExceptionType name) {

} catch (ExceptionType name) {

}

What will happen if try-catch block is not used

Let's first see what will happen if try-catch is not used in a code that throws 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 and catch

It is always good to provide an 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 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.");
 }
}

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.

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 - the 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 without having 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. Best practices for exception handling in Java
  2. Exception handling and method overriding
  3. Multiple catch blocks
  4. Nested try statements
  5. final Vs finally Vs finalize
  6. Lambda expression and exception handling
  7. Java Exception Handling interview questions

You may also like -

No comments:

Post a Comment