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 a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.