Untitled

mail@pastecode.io avatar
unknown
plain_text
4 days ago
1.1 kB
1
Indexable
Never
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;
    }
}
Leave a Comment