Tutorials

Java Exception Handling


java try-catch


Java try block is used to wrap any code that might throw an exception.

 

The try block must be followed by either catch block or finally block or both.

Java catch block handles the exception that is caught in try block.

 

Note

  • try block must be used inside a method only.
  • catch or finally block must be used after try block only.
  • We can use multiple catch block with single try block.
  • Finally block must be used after the last catch block (if catch block is used)

 

Syntax of java try-catch:


try{

//code that may throw exception

}catch(ExceptionClassName  refObject){

//catch body

}

 

Syntax of java try-finally:


try{

//code that may throw exception

}finally{

}

 

Syntax of java try-catch-finally:

 

try{

//code that may throw exception

}catch(ExceptionClassName  refObject){

//catch body

}finally{

//finally body

}

 

Example:


package exceptionHandling;

public class HandledException {

      public static void main(String[] args) {

            int a = 15;
            int b = 0;

            try{

                  int div1 = a/b;
                  System.out.println("Result div1:"+ div1);

            }catch(Exception e){
                 System.out.println("Exception occurred while performing division");
            }

            int mul = a*b;
            System.out.println("Result of multiplication:"+ mul);
      }
}

OUTPUT:
Exception occurred while performing division
Result of multiplication: 0

How above code works?

Since division by 0 is not allowed so int div1 = a/b will throw Exception.

We have seen in previous chapter that if try-catch is not used then the program would stop abruptly hampering other section of the code from executing.

But since the part of code that may throw exception is surrounded by try-catch so in case exception really occurs it will be caught & handled and the appropriate action would be taken in catch block. 

 

Once the catch block gets executed, rest of the code would get executed normally. 

That's why multiplication operation after try-catch is performed, executed and the result is printed.

 

try-catch enables programmer to stop the abrupt end of the program in case any exception occurs thus helping maintain normal program flow being preserved. 



Please Share this page
Views : 74
Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!