019-003-007

Basic Multiple Catch Blocks

Easy

Problem Description

Basic Multiple Catch Blocks

In this problem, you will create a program that receives a string argument in a process method, performs integer conversion and division, and displays different error messages to standard output using individual catch blocks depending on the type of exception thrown (NumberFormatException or ArithmeticException).

Learning Objective: Understand how to handle different types of exceptions with individual catch blocks

Overview

Define a method process(String input) that performs operations where different exceptions may occur depending on the argument. Create a program that uses multiple catch blocks to output appropriate error messages for each exception type.

Specifications

Main class

  • Define static int process(String input) method
    • Convert input to an integer using Integer.parseInt(input)
    • Store the conversion result in result, calculate 100 / result, and return it (do not catch exceptions — let them propagate to the caller)
  • In the main method, execute the following 3 cases in order:
    • Call process("abc") (throws NumberFormatException)
    • Call process("0") (throws ArithmeticException)
    • Call process("4") (processes normally)
  • Wrap each process call in a try-catch with the following catch blocks:
    • Catch NumberFormatException and print "Format error: " + e.getMessage()
    • Catch ArithmeticException and print "Math error: " + e.getMessage()
    • When no exception occurs, print "Result: " + result

Output Format

Format error: For input string: "abc"
Math error: / by zero
Result: 25

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