14. Exception Handling in Java
π Exception handling in Java is a powerful mechanism that allows developers to handle runtime errors gracefully, improving program stability and user experience.
1. What is an Exception?β
- An exception is an event that disrupts the normal flow of a program's execution.
- Exceptions can be caused by various factors, such as invalid input, resource unavailability, or hardware failure.
2. Types of Exceptionsβ
Exceptions in Java can be broadly categorized into two main types:
2.1. Checked Exceptionsβ
- These are exceptions that are checked at compile-time.
- The programmer must handle them using
try-catchblocks or declare them using thethrowskeyword.
Example:β
import java.io.FileReader;
import java.io.IOException;
public class CheckedExample {
public static void main(String[] args) {
try {
FileReader fr = new FileReader("file.txt");
} catch (IOException e) {
System.out.println("File not found: " + e.getMessage());
}
}
}
2.2. Unchecked Exceptionsβ
- These exceptions are not checked at compile-time, meaning the programmer does not have to handle them explicitly.
- They extend the
RuntimeExceptionclass.
Example:β
public class UncheckedExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3};
System.out.println(numbers[3]); // This will throw ArrayIndexOutOfBoundsException
}
}
3. The Exception Hierarchyβ
- All exceptions in Java are derived from the
Throwableclass. - The hierarchy includes two main subclasses:
- Error: Represents serious problems that a reasonable application should not try to catch.
- Exception: Represents conditions that a user program should catch.
4. Exception Handling Keywordsβ
4.1. tryβ
- The
tryblock is used to wrap code that might throw an exception.
4.2. catchβ
- The
catchblock is used to handle the exception.
Example:β
try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
}
4.3. finallyβ
- The
finallyblock is used to execute code regardless of whether an exception is thrown or not. It is typically used for cleanup activities.
Example:β
try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Handle exception
} finally {
// Cleanup code (always executes)
}
4.4. throwβ
- The
throwkeyword is used to explicitly throw an exception.
Example:β
public void validateAge(int age) {
if (age < 18) {
throw new IllegalArgumentException("Age must be at least 18");
}
}
4.5. throwsβ
- The
throwskeyword is used in method declarations to specify that a method can throw exceptions.
Example:β
public void readFile() throws IOException {
// Code that may throw an IOException
}
5. Custom Exceptionsβ
You can create your own exceptions by extending the Exception class.
Example:β
public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
public class CustomExceptionExample {
public static void main(String[] args) {
try {
throw new CustomException("This is a custom exception!");
} catch (CustomException e) {
System.out.println(e.getMessage());
}
}
}
6. Summary of Exception Handlingβ
| Feature | Description |
|---|---|
| Definition | Mechanism to handle runtime errors. |
| Types | Checked and Unchecked exceptions. |
| Hierarchy | Derived from Throwable. |
| Keywords | try, catch, finally, throw, throws. |
| Custom Exceptions | Extend the Exception class to create your own exceptions. |
Exception handling is essential for building robust Java applications that can gracefully handle errors and maintain a good user experience.