Answer
Exception Handling in Java
Exception handling prevents abnormal program termination when runtime errors occur.
Exception Hierarchy
CODE
Throwable
├── Error (JVM errors — don't catch these)
│ ├── OutOfMemoryError
│ └── StackOverflowError
└── Exception
├── Checked (must handle — compiler enforces)
│ ├── IOException
│ ├── SQLException
│ └── FileNotFoundException
└── Unchecked (RuntimeException — optional to handle)
├── NullPointerException
├── ArrayIndexOutOfBoundsException
├── IllegalArgumentException
└── NumberFormatException
try-catch-finally
Java
public void readFile(String path) {
FileReader reader = null;
try {
reader = new FileReader(path); // might throw FileNotFoundException
// risky code
int data = reader.read(); // might throw IOException
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
} catch (IOException e) {
System.out.println("IO error: " + e.getMessage());
} finally {
// Always runs — good for cleanup
try { if (reader != null) reader.close(); } catch (IOException e) {}
}
}
Multiple Catch + Multi-catch (Java 7+)
Java
try {
String s = null;
s.length(); // NullPointerException
} catch (NullPointerException | IllegalArgumentException e) {
// Handle both with single catch (Java 7+)
System.out.println("Error: " + e.getMessage());
}
throw — Manually Throw Exception
Java
public void setAge(int age) {
if (age < 0 || age > 150) {
throw new IllegalArgumentException("Invalid age: " + age);
}
this.age = age;
}
// Caller must handle it
try {
setAge(-5);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage()); // "Invalid age: -5"
}
throws — Declare Exception in Signature
Java
// Method declares it MIGHT throw — caller must handle
public void connectDB() throws SQLException {
Connection conn = DriverManager.getConnection(url, user, pass);
}
// Caller handles it
try {
connectDB();
} catch (SQLException e) {
System.out.println("DB connection failed: " + e.getMessage());
}
Custom Exception
Java
public class InvalidLoginException extends RuntimeException {
public InvalidLoginException(String message) {
super(message);
}
}
// Usage
public void login(String user, String pass) {
if (!isValid(user, pass)) {
throw new InvalidLoginException("Invalid credentials for: " + user);
}
}
try-with-resources (Java 7+)
Java
// Auto-closes resources — no finally needed
try (Connection conn = getConnection();
PreparedStatement ps = conn.prepareStatement(sql)) {
ps.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
In Automation Testing
Java
@Test
public void testLogin() {
try {
driver.findElement(By.id("submit")).click();
String title = driver.getTitle();
assertEquals("Dashboard", title);
} catch (NoSuchElementException e) {
fail("Submit button not found: " + e.getMessage());
} catch (TimeoutException e) {
fail("Page took too long to load");
} finally {
takeScreenshot("login_test"); // always capture screenshot
}
}
