Java ProgramsExceptionsChecked Exception

Checked Exception in Java

beginner·  Exceptions  ·  Error Handling

Problem

A checked exception is one the compiler verifies at compile time — code that can throw one won't even compile unless it's caught or explicitly declared with throws.

Call a method that can throw a checked exception, and handle it with a try-catch.

Input
none
Output
Slept for 100ms without interruption

Java Program

Java
public class CheckedExceptionDemo { public static void main(String[] args) { try { Thread.sleep(100); // declared "throws InterruptedException" — a checked exception System.out.println("Slept for 100ms without interruption"); } catch (InterruptedException e) { System.out.println("Sleep was interrupted: " + e.getMessage()); } } }

Output

Slept for 100ms without interruption

Core Logic

Thread.sleep() is declared to throw a checked exception, so calling it forces a choice: catch it here, or declare it and pass the obligation up to the caller.

How It Works
  1. 1Thread.sleep(100) is a built-in method declared as throws InterruptedException, a checked exception.
  2. 2Because it's checked, this code would fail to compile without either a try/catch around the call or a throws clause on main itself.
  3. 3The catch (InterruptedException e) block exists to satisfy that compiler requirement, even though nothing in this simple example actually triggers it.
  4. 4Since nothing interrupts the sleep, execution falls through the try block normally and prints the success message.
The sleep completes without interruption, so the catch block never runs and the program prints "Slept for 100ms without interruption".
💡

Key Point: The compiler doesn't know or care whether the interruption is likely — it only cares that InterruptedException is checked, so every caller must account for it one way or another.

Key Concepts

checked exceptionInterruptedExceptioncompile-time enforcement

Related Programs