Basic Structure:
The try-catch block is used to handle exceptions. The code that might throw an exception is placed inside the try block, and the catch block is used to handle the exception.
try {
// Code that might throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
}public class Example2 { public static void main(String[] args) { try { int num1 = 10; int num2 = 0; // This will cause an ArithmeticException int result = num1 / num2; System.out.println("Result: " + result); } catch (ArithmeticException e) { System.out.println("Cannot divide by zero."); } }}Cannot divide by zero.xxxxxxxxxxpublic class Example2 { public static void main(String[] args) { int num1 = 10; int num2 = 0; // This will cause an ArithmeticException int result = num1 / num2; System.out.println("Result: " + result); }}Exception in thread "main" java.lang.ArithmeticException: / by zero
at Example2.main(Example2.java:7)try {
stmt-1;
stmt-2;
stmt-3;
} catch(Exception e) {
stmt-4;
}
stmt-5;