Exceptions are a mechanism for error handling in Java. Every thrown object is a subclass of Throwable. There are two main categories:
Exception, excluding RuntimeException): must be explicitly handled or declared in the method signature via throws.RuntimeException): explicit handling is not required and can occur anywhere (e.g., NullPointerException).When to use?
public void readFile(String path) throws IOException { // Checked exception — requires handling Files.readAllLines(Paths.get(path)); } public void divide(int a, int b) { int c = a / b; // Unchecked — ArithmeticException }
Can a method that does not declare throws throw a checked exception?
Answer: No, the compiler will not allow throwing a checked exception without declaring it in the method signature (throws). However, an unchecked exception can be thrown without any warnings.
void foo() { throw new IOException(); // Compilation error }
Story
In an internet bank, the customer decided to ignore the handling of
SQLExceptionsusing unchecked wrappers. This led to invisible errors during driver updates, resulting in data desynchronization.
Story
In a logging application, the log file remained locked due to an unhandled checked exception (
FileNotFoundException), which was "lost" in the call chain; the error was not handled in time, and the application could no longer write to logs.
Story
In a trading platform, the team implemented a global catch(Throwable) to "never crash." As a result, critical unchecked exceptions were masked — the application continued to run in an inconsistent state, leading to complex bugs and data loss.