try-catch statements are used in Java to handle unwanted errors during the execution of a program.
try
block.try
block is written in the catch
block.The try
block throws an Exception
class object, which is caught by the catch
block.
In the code below, we have an arithmetic error: division by zero.
public class MyClass {public static void main(String[ ] args) {int a=25;int b=5;int c=0;System.out.println(a/c); // error due to division by zeroSystem.out.println(a/b); // this will not be executedSystem.out.println(a+b); // this will not be executed}}
Due to an error in line of the program, the program is terminated and the code below is not executed at all. To prevent the termination of the entire program due to possible errors in a particular block of code, we use the try-catch statements. An example of this is shown below:
public class MyClass {public static void main(String[ ] args) {int a=25;int b=5;int c=0;try{System.out.println(a/c); // throws an exception due to division by zeroSystem.out.println(a/b); // will not be executed since exception is thrown}// this block will be executed if an exception is throwncatch(Exception e){System.out.println("Division by zero");}System.out.println(a+b); // this will execute irrespective of exception thrown or not}}
Since there was an error generated at line in the try
block, the program jumped to the catch
block instead of terminating itself. The catch
block caught the Exception
object e
and the catch block code was executed. After this, the remaining code, after the try-catch block, is executed as well.
If an exception occurs at a particular statement of the try block, the rest of the code in the try block will not be executed. So, it is recommended not to keep the code in the try block that will not throw an exception.
An error will be generated if there is a try block but no catch block.