public class ThrowExample {
// Method to divide two numbers
static int divide(int a, int b) {
if (b == 0) {
// Explicitly throwing an exception
throw new ArithmeticException(“Cannot divide by zero!”);
}
return a / b;
}
public static void main(String[] args) {
try {
int result = divide(10, 0); // Will trigger the exception
System.out.println(“Result: ” + result);
} catch (ArithmeticException e) {
System.out.println(“Exception caught: ” + e.getMessage());
}
System.out.println(“Program continues…”);
}
}
public class DivideByZeroThrows {
// Method declaring exception using throws
static int divide(int a, int b) throws ArithmeticException {
return a / b; // May throw ArithmeticException
}
public static void main(String[] args) {
try {
int result = divide(10, 0); // Calling method
System.out.println(“Result: ” + result);
} catch (ArithmeticException e) {
System.out.println(“Exception handled: Cannot divide by zero.”);
}
System.out.println(“Program continues…”);
}
}