Try Catch Block In Java With Example

Try Catch Block In Java With Example

Java Try block

Java try block cotains the code that might throw an exception.If any exception occurs in try block the control will be jumped automatically to appropriate catch block.every try block must need to have one catch block.there should not be any code between try and catch blocks.

Structure of try block


try{
//Code
}

Java Catch block

Catch block contains the exception handling code.catch block must be used after try block only.we can use multiple catch block for one try block.

Structure of catch block


try{
//Code might throw exception
}catch(exception e){
//exception handling code
}

Example



public class Test
{
public static void main(String[] args)
{
try{
System.out.println(1000/0);
}catch(Exception e)
{
System.out.println("you have got arithemetic exception");
}

}
}
}

output

-->