Java Try Catch 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

try{  
//code that may throw exception  
} catch(Exception_class_Name ref){}  

Syntax of try-finally block

try{  
//code that may throw exception  
} 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.

Example

public class NewMain {

    public static void main(String[] args) {
       
        try
        {
           int a=10/0;    //Exception
        }
        catch(ArithmeticException e)
        {
            System.out.println(e);
            System.out.println("rest of the code...");
        }      
    }
}
Output
java.lang.ArithmeticException: / by zero
rest of the code...

Share this article on