Exception Handling
Error handling in Java
Introduction
In this lesson, you'll learn about exception handling in Java. Coming from C, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In C, you're familiar with error handling in java.
Java has its own approach to error handling in java, which we'll explore step by step.
The Java Way
Let's see how Java handles this concept. Here's a typical example:
// Java - exception handling
public int divide(int a, int b) {
if (b == 0) {
throw new ArithmeticException("Division by zero");
}
return a / b;
}
// Usage
try {
int result = divide(10, 0);
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} finally {
System.out.println("Cleanup here");
}Comparing to C
Here's how you might have written similar code in C:
// C - error handling with return codes
int divide(int a, int b, int* result) {
if (b == 0) {
return -1; // error code
}
*result = a / b;
return 0; // success
}
// Usage
int result;
if (divide(10, 0, &result) == -1) {
printf("Error: division by zero\n");
} else {
printf("Result: %d\n", result);
}You may be used to different syntax or behavior.
Exceptions separate error handling from normal flow
You may be used to different syntax or behavior.
try/catch/finally blocks for handling
You may be used to different syntax or behavior.
throws declares what exceptions a method can throw
You may be used to different syntax or behavior.
finally runs regardless of exception
Step-by-Step Breakdown
1. Try-Catch-Finally
Exceptions provide structured error handling.
try {
// Code that might throw
FileReader fr = new FileReader("file.txt");
int data = fr.read();
} catch (FileNotFoundException e) {
// Handle file not found
System.out.println("File not found: " + e.getMessage());
} catch (IOException e) {
// Handle other IO errors
System.out.println("IO error: " + e.getMessage());
} finally {
// Always runs - cleanup here
System.out.println("Cleanup");
}2. Throwing Exceptions
Methods can throw exceptions and declare them in the signature.
// Declare that method throws exception
public void readFile(String path) throws IOException {
FileReader fr = new FileReader(path);
// if file doesn't exist, throws FileNotFoundException
// which is a subclass of IOException
}
// Custom exceptions
public class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
public void setAge(int age) throws InvalidAgeException {
if (age < 0) {
throw new InvalidAgeException("Age cannot be negative");
}
}3. Checked vs Unchecked
Checked exceptions must be caught or declared. Unchecked can be ignored.
// Checked - must handle or declare
// IOException, SQLException, etc.
public void read() throws IOException {
// ...
}
// Unchecked - don't need to declare
// RuntimeException, NullPointerException, etc.
public void process(String s) {
if (s == null) {
throw new NullPointerException("s cannot be null");
}
}Common Mistakes
When coming from C, developers often make these mistakes:
- Exceptions separate error handling from normal flow
- try/catch/finally blocks for handling
- throws declares what exceptions a method can throw
Key Takeaways
- Exceptions separate error handling from logic
- try/catch/finally for handling
- throw to raise, throws to declare
- Checked exceptions must be handled or declared