The try-catch mechanism in Java is used to handle runtime errors (exceptions) gracefully, preventing program termination and allowing controlled recovery.
Java executes code inside try. If an exception occurs, control immediately transfers to the matching catch block.
// Basic structure of try-catch
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}
// Handling ArithmeticException in Java
public class TryCatchDemo {
public static void main(String[] args) {
try {
int a = 20;
int b = 0;
int c = a / b;
System.out.println(c);
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero");
}
}
}
When division by zero occurs, Java throws an ArithmeticException. The program does not crash; instead, the catch block executes and prints a message.
Enter numbers to simulate execution flow. Try dividing by 0!
ArrayIndexOutOfBoundsExceptione.getMessage()