ProgrammingBackend Java Developer

What are exceptions in Java? Explain the difference between checked and unchecked exceptions and when to use each category.

Pass interviews with Hintsage AI assistant

Answer

Exceptions are a mechanism for error handling in Java. Every thrown object is a subclass of Throwable. There are two main categories:

  • Checked exceptions (subclasses of Exception, excluding RuntimeException): must be explicitly handled or declared in the method signature via throws.
  • Unchecked exceptions (subclasses of RuntimeException): explicit handling is not required and can occur anywhere (e.g., NullPointerException).

When to use?

  • Checked — for expected errors that can be handled (e.g., file operations, network errors).
  • Unchecked — for errors that indicate programming defects (e.g., incorrect array index).
Code Example
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 }

Tricky Question

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 }

Examples of real errors due to misunderstanding of the topic


Story

In an internet bank, the customer decided to ignore the handling of SQLExceptions using 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.