checked and unchecked exceptions

 

✅ 1. Checked Exceptions (Compile-Time Exceptions)

These are exceptions that the Java compiler forces you to handle. If your code might throw a checked exception, you must either:

  • Handle it using a try-catch block, or

  • Declare it using the throws keyword in the method signature

📌 Common Checked Exceptions:

  • IOException

  • FileNotFoundException

  • SQLException

  • ClassNotFoundException

📘 Example – File Handling:

import java.io.*;
public class CheckedExample { public static void main(String[] args) { try { FileReader file = new FileReader("test.txt"); // may throw FileNotFoundException BufferedReader br = new BufferedReader(file); System.out.println(br.readLine()); br.close(); } catch (IOException e) { System.out.println("File error: " + e.getMessage()); } } }

🔍 What Happens?

  • If you remove the try-catch, the compiler gives an error: unreported exception must be caught or declared to be thrown.


✅ 2. Unchecked Exceptions (Runtime Exceptions)

These are exceptions derived from RuntimeException. Java does not require you to catch or declare them. They usually represent programming bugs like invalid logic or null references.

📌 Common Unchecked Exceptions:

  • NullPointerException

  • ArithmeticException

  • ArrayIndexOutOfBoundsException

  • IllegalArgumentException

📘 Example – Divide by Zero:

public class UncheckedExample {
public static void main(String[] args) { int a = 10, b = 0; int result = a / b; // ArithmeticException at runtime System.out.println("Result: " + result); } }

🔍 What Happens?

  • The code compiles without error.

  • But at runtime, it crashes with:
    Exception in thread "main" java.lang.ArithmeticException: / by zero


🔄 Key Differences Summary:

FeatureChecked ExceptionUnchecked Exception
Checked at Compile-Time?✅ Yes    ❌ No
Must be handled?✅ Yes (try-catch or throws)    ❌ No (optional)
Inherits fromException    RuntimeException
ExamplesIOException, SQLException   NullPointerException, ArithmeticException
Common useExternal errors (I/O, DB)    Code bugs (nulls, logic)

💡 Best Practice

  • Handle checked exceptions properly with meaningful messages.

  • Avoid unchecked exceptions by writing safe code (e.g., check for nulls, bounds).

Comments

Popular posts from this blog

Object Oriented Programming PBCST304 KTU BTech CS Semester 3 2024 Scheme - Dr Binu V P

Introduction to Java Programming

Inheritance and Polymorphism