Answer
Checked vs Unchecked Exceptions
Checked Exceptions
Must be handled at compile time ā either with try-catch or declared with throws. The compiler enforces this. Extend Exception (but not RuntimeException).
Java
// Reading a file ā checked exception
public void readFile(String path) throws IOException {
FileReader reader = new FileReader(path); // FileNotFoundException (checked)
reader.read(); // IOException (checked)
reader.close();
}
// Caller must handle it
try {
readFile("data.txt");
} catch (IOException e) {
System.out.println("File error: " + e.getMessage());
}
Common Checked Exceptions:
- ā
IOExceptionā file operations - ā
FileNotFoundExceptionā file not found - ā
SQLExceptionā database errors - ā
ClassNotFoundExceptionā class loading - ā
InterruptedExceptionā thread interrupted
Unchecked Exceptions (RuntimeException)
NOT enforced by compiler ā can choose to handle or not. Usually indicate programming bugs. Extend RuntimeException.
Java
// These don't require try-catch (but will crash at runtime if not handled)
String s = null;
s.length(); // NullPointerException (unchecked)
int[] arr = new int[3];
arr[10] = 5; // ArrayIndexOutOfBoundsException (unchecked)
int result = 10 / 0; // ArithmeticException (unchecked)
String num = "abc";
int n = Integer.parseInt(num); // NumberFormatException (unchecked)
Object obj = "hello";
Integer i = (Integer) obj; // ClassCastException (unchecked)
Common Unchecked Exceptions:
- ā
NullPointerExceptionā null reference - ā
ArrayIndexOutOfBoundsExceptionā invalid array index - ā
ClassCastExceptionā invalid type cast - ā
NumberFormatExceptionā invalid string to number - ā
ArithmeticExceptionā divide by zero - ā
StackOverflowErrorā infinite recursion - ā
IllegalArgumentExceptionā invalid argument - ā
IllegalStateExceptionā invalid state
Creating Custom Exceptions
Java
// Custom checked exception
public class DatabaseConnectionException extends Exception {
public DatabaseConnectionException(String message) {
super(message);
}
public DatabaseConnectionException(String message, Throwable cause) {
super(message, cause);
}
}
// Custom unchecked exception
public class InvalidPageStateException extends RuntimeException {
public InvalidPageStateException(String page) {
super("Page not in expected state: " + page);
}
}
// Usage
public void connectToDb() throws DatabaseConnectionException {
try {
// DB connection attempt
} catch (SQLException e) {
throw new DatabaseConnectionException("Failed to connect", e);
}
}
Exception Hierarchy
CODE
Throwable
āāā Error (don't catch ā JVM issues)
ā āāā OutOfMemoryError
ā āāā StackOverflowError
āāā Exception
āāā CHECKED (must handle)
ā āāā IOException
ā āāā SQLException
ā āāā ClassNotFoundException
āāā RuntimeException (UNCHECKED ā optional)
āāā NullPointerException
āāā IllegalArgumentException
āāā ArrayIndexOutOfBoundsException
Best Practices
Java
// ā
Catch specific exceptions, not generic Exception
try {
connectToDb();
} catch (DatabaseConnectionException e) {
log.error("DB error", e);
} catch (IOException e) {
log.error("IO error", e);
}
// ā Avoid swallowing exceptions silently
try { ... } catch (Exception e) { } // BAD ā hides errors
// ā
Always log or rethrow
try { ... } catch (Exception e) {
log.error("Unexpected error", e);
throw new RuntimeException("Operation failed", e);
}
