Archives for 

try/catch/finally in Java

try catch in Java

Java is having techniques to handle exceptions. Here in this section we are going to discuss about try catch in Java. One finally block is there as optional with try/catch block.

try catch in Java

The try/catch/finally clause in Java is using to handle exceptions. The piece of code that may throw exception needs to put in the try block. If some logic needs to be performed once an exception occurs() then the logic needs to be put in the catch block.

try{

//code that throws exception

     }catch(){

//logic to handle exceptions

    }

Any number of catch blocks  can be put for a single try clause.

try{

      }catch(Exception type1){

     //logic for handling Exception type1

      }catch(Exception type2){

//logic for handling Exception type2

      }

If a common code snippet needs to be performed for all types of exceptions throwing then , we can put a finally block after all catch blocks.

try{

}catch(Exception type1){

//code for handling  type1

}catch(Exception type2){

//code for handling type2

}finally{

//common code snippet for all types of exceptions

}

Now let us see an example.It divides 10 by 0(zero) .Arithmetic Exception will be thrown .In the catch block we are just printing the stack trace of the exception and a status message saying an exception occurred.

public class DivSample {
public DivSample() {

}
public void getException() {
int number = 0;
try {
int result = 10 / number;
} catch (ArithmeticException e) {
System.out.println("An exception has been thrown");
e.printStackTrace();
}
}
public static void main(String[] args) {
DivSample sample = new DivSample();
sample.getException();
}
}

Output

An exception has been thrown

java.lang.ArithmeticException: / by zero

    at com.arithsample.DivSample.getException(DivSample.java:16)

    at com.arithsample.DivSample.main(DivSample.java:26)

     ——————————————————

    ——————————————————