Unit 11: File Input and Output

Exception Handling in Java

Introduction to Exception Handling

In the programming world, unexpected scenarios or errors are bound to occur. Java provides a built-in mechanism called exception handling to gracefully handle such situations, ensuring the program doesn't crash and can provide informative feedback to users.


The Essence of Exceptions

Understanding Exceptions

An exception is an unwanted or unexpected event, which occurs during the execution of a program. This disrupts the normal flow of program instructions.

Example:

Trying to divide by zero or accessing an out-of-bounds index in an array.


Java's Built-in Exceptions

Java provides a rich set of built-in exceptions. Some common ones include:

  • ArithmeticException: Occurs during arithmetic operations like division by zero.
  • NullPointerException: Indicates an attempt to access an object or call a method on an object that is currently null.
  • ArrayIndexOutOfBoundsException: Occurs when indexing an array outside its bounds.

Remember!

Every exception in Java is an instance of a class derived from the Throwable class.


Handling Exceptions

The try-catch Block

The primary mechanism for handling exceptions. It allows you to enclose the "risky" code that might throw an exception.

try {
    // code that might throw an exception
} catch (ExceptionType e) {
    // code to handle the exception
}

Example:

try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero!");
}

Propagating Exceptions

The throws Keyword

In some scenarios, you might not want to handle the exception in the current method but rather let it propagate to a higher method in the call stack:

public void riskyMethod() throws SomeException {
    // some code
}

Note

Using throws doesn't handle the exception; it just tells the caller that this method might throw the mentioned exception.


Multiple Catch Blocks and Finally

You can use multiple catch blocks to handle different exception types:

try {
    // code that might throw multiple exceptions
} catch (ExceptionType1 e1) {
    // handle exception type 1
} catch (ExceptionType2 e2) {
    // handle exception type 2
}

The finally block always executes, whether an exception was thrown or not:

try {
    // risky code
} catch (ExceptionType e) {
    // handle exception
} finally {
    // cleanup code, always runs
}

Summary

Exception handling in Java is a robust mechanism that provides a safety net for potential run-time errors. Mastering it ensures your programs are resilient, user-friendly, and professional, by gracefully handling unforeseen situations.


References


AP CSA Homework Assignment

Assignment: Exception Handling Drill

Instructions

  1. Write a Java program that prompts the user to input an integer.
  2. Use exception handling to ensure the input is indeed an integer. If not, provide feedback and allow the user to try again.
  3. Implement additional checks: ensure the number is positive and below 100.
  4. Reflect on the experience: How does exception handling enhance user experience? Can you think of real-world applications where it's crucial?
Previous
Java API