US Trends

what is checked exception in java

A checked exception in Java is a type of exception that the compiler forces you to handle either with a try‑catch block or by declaring it with throws in the method signature.

What “checked” really means

  • Checked at compile time: The compiler checks whether any code can throw a checked exception and warns or errors if you don’t handle or declare it.
  • Subclasses ofException, excluding RuntimeException: Anything that extends Exception but not RuntimeException counts as a checked exception.
  • Typical examples: IOException, SQLException, FileNotFoundException, InterruptedException.

How checked exceptions are used

When a method can throw a checked exception, you must:

  • Catch it explicitly:

    java
    
    try {
        FileReader file = new FileReader("missing.txt");
    } catch (FileNotFoundException e) {
        System.out.println("File not found: " + e.getMessage());
    }
    

This forces the programmer to think about and plan for possible failure paths.

  • Or declare it inthrows:

    java
    
    void readFile() throws IOException { // let caller handle it
        FileReader file = new FileReader("data.txt");
    }
    

The caller then must handle or re‑declare it.

Why checked exceptions exist

  • Recoverable, predictable problems: They model things that can reasonably go wrong even when the code is correct, like file or network issues, database errors, or parsing invalid input.
  • Design contract: They make the API contract explicit: “this method may fail due to X, and you must decide what to do.”

Checked vs unchecked exceptions (mini‑table)

Aspect| Checked exception| Unchecked exception (RuntimeException)
---|---|---
When checked| At compile time 16| At runtime 13
Base class| Exception (not RuntimeException) 17| RuntimeException or Error 15
Mandatory handling?| Yes (try‑catch or throws) 159| No (optional) 13
Typical use case| Recoverable external problems 135| Programming bugs (e.g., NullPointerException) 13
Example (I/O)| IOException, FileNotFoundException 15| –

Quick intuition in one line

A checked exception in Java is a “planned failure” the compiler insists you acknowledge and handle, usually because it represents a real‑world problem (like missing files or broken networks) rather than a logic bug in your code.

Information gathered from public forums or data available on the internet and portrayed here.