Java Try Catch Block


In Java, a try block is placed around the code that might throw an exception. It should be used among the method.

Java try block should be followed by either catch or finally block.

Syntax:

 try {
	//	Code that might 
    	throw an exception
}catch (ExceptionName e) {
   //Catch block
}
Java Exception

Catch Block

A catch block is used to handle an exception by declaring the type of exception you are trying to catch. It should be used after the try block.

Example

 public class ExceptionHandling{
    public static void main(String args[]){  
        try{  
            int a=1/0;  
        }
        catch(ArithmeticException ae){
            System.out.println(ae);
        } 
        finally{
            System.out.println("Always execute");  
        }
  	}  
}  

Finally Block

A finally block of code always executes whether an exception is handled or not.

 

A finally block is also used for clean up processing e.g like closing connection, closing stream, closing a file, etc.




Onlinetpoint is optimized for basic learning, practice and more. Examples are well checked and working examples available on this website but we can't give assurity for 100% correctness of all the content. This site under copyright content belongs to Onlinetpoint. You agree to have read and accepted our terms of use, cookie and privacy policy.