Basic Multiple Catch Blocks
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
inputto an integer usingInteger.parseInt(input) - Store the conversion result in
result, calculate100 / result, and return it (do not catch exceptions — let them propagate to the caller)
- Convert
- In the
mainmethod, execute the following 3 cases in order:- Call
process("abc")(throws NumberFormatException) - Call
process("0")(throws ArithmeticException) - Call
process("4")(processes normally)
- Call
- Wrap each
processcall in a try-catch with the following catch blocks:- Catch
NumberFormatExceptionand print"Format error: " + e.getMessage() - Catch
ArithmeticExceptionand print"Math error: " + e.getMessage() - When no exception occurs, print
"Result: " + result
- Catch
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