</>

Technology

Core Java

Difficulty

Intermediate

Interview Question

What are checked and unchecked exceptions in Java?

Answer

Checked vs Unchecked Exceptions

Checked Exceptions

Must be handled at compile time — either with try-catch or declared with throws. The compiler enforces this. Extend Exception (but not RuntimeException).

Java
// Reading a file — checked exception
public void readFile(String path) throws IOException {
    FileReader reader = new FileReader(path); // FileNotFoundException (checked)
    reader.read();                            // IOException (checked)
    reader.close();
}

// Caller must handle it
try {
    readFile("data.txt");
} catch (IOException e) {
    System.out.println("File error: " + e.getMessage());
}

Common Checked Exceptions:

  • āœ“IOException — file operations
  • āœ“FileNotFoundException — file not found
  • āœ“SQLException — database errors
  • āœ“ClassNotFoundException — class loading
  • āœ“InterruptedException — thread interrupted

Unchecked Exceptions (RuntimeException)

NOT enforced by compiler — can choose to handle or not. Usually indicate programming bugs. Extend RuntimeException.

Java
// These don't require try-catch (but will crash at runtime if not handled)
String s = null;
s.length();           // NullPointerException (unchecked)

int[] arr = new int[3];
arr[10] = 5;          // ArrayIndexOutOfBoundsException (unchecked)

int result = 10 / 0; // ArithmeticException (unchecked)

String num = "abc";
int n = Integer.parseInt(num); // NumberFormatException (unchecked)

Object obj = "hello";
Integer i = (Integer) obj;    // ClassCastException (unchecked)

Common Unchecked Exceptions:

  • āœ“NullPointerException — null reference
  • āœ“ArrayIndexOutOfBoundsException — invalid array index
  • āœ“ClassCastException — invalid type cast
  • āœ“NumberFormatException — invalid string to number
  • āœ“ArithmeticException — divide by zero
  • āœ“StackOverflowError — infinite recursion
  • āœ“IllegalArgumentException — invalid argument
  • āœ“IllegalStateException — invalid state

Creating Custom Exceptions

Java
// Custom checked exception
public class DatabaseConnectionException extends Exception {
    public DatabaseConnectionException(String message) {
        super(message);
    }
    public DatabaseConnectionException(String message, Throwable cause) {
        super(message, cause);
    }
}

// Custom unchecked exception
public class InvalidPageStateException extends RuntimeException {
    public InvalidPageStateException(String page) {
        super("Page not in expected state: " + page);
    }
}

// Usage
public void connectToDb() throws DatabaseConnectionException {
    try {
        // DB connection attempt
    } catch (SQLException e) {
        throw new DatabaseConnectionException("Failed to connect", e);
    }
}

Exception Hierarchy

CODE
Throwable
ā”œā”€ā”€ Error (don't catch — JVM issues)
│   ā”œā”€ā”€ OutOfMemoryError
│   └── StackOverflowError
└── Exception
    ā”œā”€ā”€ CHECKED (must handle)
    │   ā”œā”€ā”€ IOException
    │   ā”œā”€ā”€ SQLException
    │   └── ClassNotFoundException
    └── RuntimeException (UNCHECKED — optional)
        ā”œā”€ā”€ NullPointerException
        ā”œā”€ā”€ IllegalArgumentException
        └── ArrayIndexOutOfBoundsException

Best Practices

Java
// āœ… Catch specific exceptions, not generic Exception
try {
    connectToDb();
} catch (DatabaseConnectionException e) {
    log.error("DB error", e);
} catch (IOException e) {
    log.error("IO error", e);
}

// āŒ Avoid swallowing exceptions silently
try { ... } catch (Exception e) { }  // BAD — hides errors

// āœ… Always log or rethrow
try { ... } catch (Exception e) {
    log.error("Unexpected error", e);
    throw new RuntimeException("Operation failed", e);
}

Follow AutomateQA

Related Topics