Using Try And Catch Statement In Java

The Try Block

Try and Catch statement consists of two blocks namely, try block and catch block. The Try block contains the code in which an exception or error might occur. The try block must be followed by a catch block.

The Catch Block

After the try block, there must be at least one catch block. There can also be multiple catch blocks. It’s executed only when there’s an exception in the code present in the try block.

Syntax

try{
//Code vulnerable to exceptions
}
catch (Exception e){
//Show error to user in some way
//Use e.getMessage() to get exact error message
}

Flow Control

First of all, code of try block starts being executed. If there’s no exception, control gets out of try and catch statement. Otherwise, as soon as an exception is caught, control moves to catch block and execute the code present there like to show up the error.

Example

public class Main {

public static void main(String[] args) {
try{
int a,b;
          a=100;
          b=a/0;
}
catch (Exception e){
            System.out.println("Division by zero isn't possible");
}
}
}

In this program, two variables are declared namely, a and b. We assign some finite value to a, let’s say, 100. Now b stores the outcome of a divided by 0. Now since it’s impossible to divide any number by 0, ArithmaticException has occurred and the catch block gets the control which further shows the error as specified.

Related posts