How to use try-catch statements in Java

try-catch statements are used in Java to handle unwanted errors during the execution of a program.

  • Try: The block of code to be tested for errors while the program is being executed is written in the try block.
  • Catch: The block of code that is executed when an error occurs in the try block is written in the catch block.

The try block throws an Exception class object, which is caught by the catch block.

svg viewer

Why use try-catch statements?

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 zero
System.out.println(a/b); // this will not be executed
System.out.println(a+b); // this will not be executed
}
}

Due to an error in line 66 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 zero
System.out.println(a/b); // will not be executed since exception is thrown
}
// this block will be executed if an exception is thrown
catch(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 77 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.

working of try-catch blocks
working of try-catch blocks
Copyright ©2024 Educative, Inc. All rights reserved