0
0
Javaprogramming~20 mins

Multiple catch blocks in Java - Mini Project: Build & Apply

Choose your learning style9 modes available
Handling Multiple Exceptions with Multiple Catch Blocks in Java
πŸ“– Scenario: Imagine you are writing a simple Java program that reads numbers from an array and divides a fixed number by each element. Sometimes, the array might contain zero or invalid data, which can cause errors.
🎯 Goal: You will create a Java program that uses try with multiple catch blocks to handle different types of exceptions separately.
πŸ“‹ What You'll Learn
Create an integer array called numbers with the values 10, 0, 5, -3
Create an integer variable called fixedNumber and set it to 100
Use a for loop with variable i to iterate over numbers
Inside the loop, use a try block to divide fixedNumber by numbers[i]
Add catch blocks to handle ArithmeticException and ArrayIndexOutOfBoundsException
Print specific messages inside each catch block
Print the result of the division inside the try block if no exception occurs
πŸ’‘ Why This Matters
🌍 Real World
Handling multiple exceptions is common in real-world programs where different errors can happen, such as file errors, network problems, or invalid user input.
πŸ’Ό Career
Knowing how to use multiple catch blocks helps you write robust Java applications that don't crash unexpectedly and provide clear error messages.
Progress0 / 4 steps
1
Create the data setup
Create an integer array called numbers with the values 10, 0, 5, -3 and an integer variable called fixedNumber set to 100.
Java
Need a hint?

Use int[] numbers = {10, 0, 5, -3}; to create the array and int fixedNumber = 100; for the fixed number.

2
Add a for loop to iterate over the array
Add a for loop with variable i that goes from 0 to numbers.length - 1 to iterate over the numbers array.
Java
Need a hint?

Use for (int i = 0; i < numbers.length; i++) to loop through the array.

3
Add try block with multiple catch blocks
Inside the for loop, add a try block that divides fixedNumber by numbers[i] and prints the result. Add two catch blocks: one for ArithmeticException that prints "Cannot divide by zero at index i" and one for ArrayIndexOutOfBoundsException that prints "Index i is out of bounds".
Java
Need a hint?

Use try to attempt the division. Catch ArithmeticException to handle division by zero and ArrayIndexOutOfBoundsException for invalid indexes.

4
Print the output
Run the program and print the output to the console. Use System.out.println inside the try and catch blocks as already written.
Java
Need a hint?

Run the program. You should see results for valid divisions and messages for division by zero.