Java Multiple Catch Blocks Tutorial 🎯

beginner
16 min

Java Multiple Catch Blocks Tutorial 🎯

Welcome back to CodeYourCraft! Today, we're diving into one of the more advanced topics in Java: Multiple Catch Blocks. Let's get started!

Understanding Exception Handling in Java 📝

Before we delve into multiple catch blocks, let's quickly review what exception handling is in Java. Exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. Java provides a mechanism to handle exceptions using try, catch, and finally blocks.

The Need for Multiple Catch Blocks 💡

Sometimes, a piece of code can throw multiple exceptions. To handle each exception separately, we use multiple catch blocks. This allows us to write specific catch blocks for specific exceptions, ensuring our code is more robust and easier to maintain.

Java Multiple Catch Blocks - Syntax and Examples 🎯

In Java, we can catch multiple exceptions by defining multiple catch blocks. The order of the catch blocks matters, as the JVM (Java Virtual Machine) looks for the most specific exception match. Here's the syntax for multiple catch blocks:

java
try { // code that might throw an exception } catch (ExceptionType1 e1) { // handle exception of type ExceptionType1 } catch (ExceptionType2 e2) { // handle exception of type ExceptionType2 } ...

Example 1: Handling Multiple Exceptions in a Simple Calculator 💡

Let's build a simple calculator that calculates the sum, difference, product, and quotient of two numbers. We'll handle the ArithmeticException that occurs when division by zero.

java
import java.util.Scanner; public class SimpleCalculator { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the first number: "); double num1 = scanner.nextDouble(); System.out.print("Enter the second number: "); double num2 = scanner.nextDouble(); System.out.println("Choose an operation:"); System.out.println("1. Addition"); System.out.println("2. Subtraction"); System.out.println("3. Multiplication"); System.out.println("4. Division"); System.out.print("Enter your choice: "); int choice = scanner.nextInt(); double result; double quotient; switch (choice) { case 1: result = num1 + num2; break; case 2: result = num1 - num2; break; case 3: result = num1 * num2; break; case 4: quotient = num1 / num2; try { result = quotient; } catch (ArithmeticException e) { System.err.println("Error: Division by zero is not allowed."); System.exit(0); } break; default: System.out.println("Invalid choice!"); System.exit(0); } System.out.printf("The result is: %.2f", result); } }

In the above example, we have a single try block to enclose the division operation, and a single catch block to handle the ArithmeticException that occurs when division by zero.

Example 2: Handling Multiple Exceptions in a File Reader 💡

Let's create a simple file reader that reads a text file and displays its content. We'll handle two exceptions: FileNotFoundException and IOException.

java
import java.io.*; public class FileReader { public static void main(String[] args) { System.out.print("Enter the file path: "); Scanner scanner = new Scanner(System.in); String filePath = scanner.nextLine(); try (FileReader fileReader = new FileReader(filePath); BufferedReader bufferedReader = new BufferedReader(fileReader)) { String line; while ((line = bufferedReader.readLine()) != null) { System.out.println(line); } } catch (FileNotFoundException e1) { System.err.println("Error: The file could not be found."); } catch (IOException e2) { System.err.println("Error: An I/O error occurred while reading the file."); } } }

In this example, we have two catch blocks to handle the two types of exceptions that might occur while reading a file.

Quiz Time 🎯

Quick Quiz
Question 1 of 1

Which type of exception is handled in the first `catch` block in the FileReader example?

That's it for today! We've covered the basics of Java multiple catch blocks. Stay tuned for more in-depth lessons on exception handling and other Java topics here at CodeYourCraft. Happy coding! 🚀