Exception Handling
Overview
Overview
Exception handling in Java is a mechanism to handle runtime errors, ensuring the normal flow of the application. It uses try, catch, finally, throw, and throws keywords.
Checked vs Unchecked Exceptions
- Checked Exceptions: Must be declared in the method signature using
throwsor handled withtry-catch.- Example:
IOException,SQLException
- Example:
- Unchecked Exceptions: Do not need to be declared or handled.
- Example:
ArithmeticException,NullPointerException
- Example:
Custom Exceptions
You can create your own exceptions by extending the Exception class.
Exception Hierarchy
Exception Hierarchy
The following diagram illustrates the hierarchy of exceptions in Java:
flowchart TD
Object --> Throwable
Throwable --> Error
Throwable --> Exception
Error --> ThreadDeath
Error --> IOError
Error --> OutOfMemoryError
Error --> VirtualMachineError
Exception --> RuntimeException
Exception --> IOException
Exception --> SQLException
RuntimeException --> ArithmeticException
RuntimeException --> NullPointerException
RuntimeException --> IndexOutOfBoundsException
throws Keyword
throws Keyword
- The
throwskeyword in Java is used in a method declaration to specify the exceptions that the method can throw. - It informs the caller of the method about the exceptions that need to be handled or declared further.
import java.io.IOException;
public class Example {
public void readFile() throws IOException {
throw new IOException("File not found");
}
public static void main(String[] args) {
Example example = new Example();
try {
example.readFile();
} catch (IOException e) {
System.out.println("Caught exception: " + e.getMessage());
}
}
}
- The
throwskeyword is used to declare checked exceptions. - It does not handle the exception; it only propagates it to the caller.
- Multiple exceptions can be declared, separated by commas.
- Unchecked exceptions (subclasses of
RuntimeException) do not need to be declared withthrows.
Try with Resources
Try with Resources
- The "try-with-resources" statement in Java is used to automatically close resources (like files, sockets, or database connections) that implement the
AutoCloseableinterface. - Introduced in Java 7, it simplifies resource management and reduces boilerplate code.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Example {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new FileReader("example.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("Error reading file: " + e.getMessage());
}
}
}
- Resources declared in the
tryblock are automatically closed at the end of the block. - Multiple resources can be declared, separated by semicolons (
;). - The resources must implement the
AutoCloseableinterface (or its subinterface,Closeable). - Reduces the need for explicit
finallyblocks to close resources.