Untitled
unknown
plain_text
a year ago
1.1 kB
7
Indexable
import java.util.Scanner;
public class ExceptionHandlingExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numerator = 0;
int denominator = 0;
try {
System.out.print("Enter numerator: ");
numerator = scanner.nextInt();
System.out.print("Enter denominator: ");
denominator = scanner.nextInt();
// This may throw an ArithmeticException if denominator is zero
int result = divide(numerator, denominator);
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed.");
} catch (Exception e) {
System.out.println("Error: Invalid input. Please enter integers only.");
} finally {
System.out.println("Execution completed.");
scanner.close();
}
}
// Method to perform division
public static int divide(int num, int denom) {
return num / denom;
}
}
Editor is loading...
Leave a Comment