AdSense

AdSense3

Saturday, 6 September 2014

Java try-catch

Java try block

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

Syntax of java try-catch

  1. try{  
  2. //code that may throw exception  
  3. }catch(Exception_class_Name ref){}  

Syntax of try-finally block

  1. try{  
  2. //code that may throw exception  
  3. }finally{}  

Java catch block

Java catch block is used to handle the Exception. It must be used after the try block only.
You can use multiple catch block with a single try.

Problem without exception handling

Let's try to understand the problem if we don't use try-catch block.
  1. public class Testtrycatch1{  
  2.   public static void main(String args[]){  
  3.       int data=50/0;//may throw exception  
  4.       System.out.println("rest of the code...");  
  5. }  
  6. }  

Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
As displayed in the above example, rest of the code is not executed (in such case, rest of the code... statement is not printed).
There can be 100 lines of code after exception. So all the code after exception will not be executed.

Solution by exception handling

Let's see the solution of above problem by java try-catch block.
  1. public class Testtrycatch2{  
  2.   public static void main(String args[]){  
  3.    try{  
  4.       int data=50/0;  
  5.    }catch(ArithmeticException e){System.out.println(e);}  
  6.    System.out.println("rest of the code...");  
  7. }  
  8. }  

Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...
Now, as displayed in the above example, rest of the code is executed i.e. rest of the code... statement is printed.

Internal working of java try-catch block

internal working of try-catch block
The JVM firstly checks whether the exception is handled or not. If exception is not handled, JVM provides a default exception handler that performs the following tasks:
  • Prints out exception description.
  • Prints the stack trace (Hierarchy of methods where the exception occurred).
  • Causes the program to terminate.
But if exception is handled by the application programmer, normal flow of the application is maintained i.e. rest of the code is executed.

No comments:

Post a Comment