019-003-012

Multiple Catch Order and Hierarchy

Medium

Problem Description

Multiple Catch Order and Hierarchy

In this problem: You will arrange multiple catch clauses in the correct order and catch exceptions appropriately based on the hierarchy.

Learning Objective: Understand the relationship between catch clause order and exception inheritance hierarchy

Overview

Catch clauses must be ordered from more specific to more general exception types. Reversing this order causes a compilation error.

Specifications

  • Calculator class:
    • divide(int a, int b): returns a / b
    • calculate(String numStr, int divisor): converts string to integer then calls divide
  • In Main, test three cases:
    1. calculate("10", 2) - normal (result: 5)
    2. calculate("10", 0) - ArithmeticException
    3. calculate("abc", 2) - NumberFormatException
  • Catch clauses ordered: ArithmeticException, NumberFormatException, Exception

Output Format

Result: 5
Arithmetic error: / by zero
Format error: For input string: "abc"

Ready to Try Running Code?

Log in to access the code editor and execute your solutions for this problem.

Don't have an account?

Sign Up