Monday, January 29, 2018

Try-Catch in Java



Java try block should be used inside the method and it is mainly used in code that might Throw Exception.

Note : Always Try block should be followed by either Catch block or Finally block.

Syntax of Try - Catch block and Try - Finally block is :

Try - Catch :

try {

        // Inside Code

} catch (Exception)
{

      // Catch Exception

}

Try - Finally :

try {

         //Inside Code
}finally (Exception)
{

     // Catch Exception

}

Java Catch block :

Catch block is used to Handle Exception which is thrown from the Try Block.

Here we can use many Catch block for a Try block.

What are all the problems we will get , while running the code with out Try - Catch block.

Code (Without Try-Catch):
  
public class Test{   
public static void main(String args[]){   
int data=50/0;//may throw exception   
System.out.println("rest of the code...");   
}
}  

Here the error will be "Exception in thread main java.lang.ArithmeticException:/ by zero".

But the Execution will stop at the same point , Where the error occurs . it will not continue execution and print the "rest of the code" line.

Code(With Try-Catch) :

public class Test{ 
public static void main(String args[]){ 
try{ 
int data=50/0; 
}catch(ArithmeticException e){System.out.println(e);} 
System.out.println("rest of the code..."); 

}


Here the error will be "Exception in thread main java.lang.ArithmeticException:/ by zero". 
With "rest of the code" line.







Thanks,

A M Balaji


   


No comments:

Post a Comment