Java.Core.What is a checked and unchecked exception?

In Java, exceptions are classified into checked and unchecked exceptions based on whether the compiler forces handling at compile time.


1. Checked Exceptions (Compile-Time Exceptions)

Definition:
Checked exceptions are exceptions that the compiler forces you to handle. You must either:

  • Use a try-catch block OR
  • Declare the exception using throws in the method signature.

Why?
Checked exceptions represent recoverable conditions (such as file I/O or database errors) that are beyond the programmer’s control.

Examples of Checked Exceptions:

ExceptionWhen It Occurs
IOExceptionProblems reading/writing files
SQLExceptionDatabase connection failure
FileNotFoundExceptionFile does not exist
InterruptedExceptionThread is interrupted
ClassNotFoundExceptionJava class is missing at runtime

Example: Handling Checked Exception with try-catch

import java.io.*;

public class CheckedExceptionExample {
    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());
        } catch (FileNotFoundException e) {
            System.out.println("File not found: " + e.getMessage());
        } catch (IOException e) {
            System.out.println("Error reading file: " + e.getMessage());
        }
    }
}

Example: Declaring Checked Exception with throws

import java.io.*;

public class CheckedExample {
    public static void readFile() throws IOException {
        FileReader file = new FileReader("test.txt"); // Must be handled or declared
        BufferedReader br = new BufferedReader(file);
        System.out.println(br.readLine());
    }

    public static void main(String[] args) {
        try {
            readFile();
        } catch (IOException e) {
            System.out.println("Handled: " + e.getMessage());
        }
    }
}

2. Unchecked Exceptions (Runtime Exceptions)

🚀 Definition:
Unchecked exceptions occur due to programming mistakes and are not forced to be handled by the compiler.

🚀 Why?
Unchecked exceptions occur because of incorrect code logic, and the best practice is to prevent them through proper coding rather than catching them.

🚀 Examples of Unchecked Exceptions (RuntimeException and its subclasses):

ExceptionWhen It Occurs
NullPointerExceptionAccessing a null object
ArrayIndexOutOfBoundsExceptionUsing an invalid index in an array
ArithmeticExceptionDivision by zero
IllegalArgumentExceptionPassing invalid method arguments
ClassCastExceptionTrying to cast an incompatible object

🚀 Example: Unchecked Exception (NullPointerException)

public class UncheckedExceptionExample {
    public static void main(String[] args) {
        String str = null;
        System.out.println(str.length()); // NullPointerException
    }
}

🛠 Better Approach: Avoid null values.

if (str != null) {
    System.out.println(str.length());
} else {
    System.out.println("String is null");
}

🚀 Example: Unchecked Exception (ArrayIndexOutOfBoundsException)

public class ArrayExample {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3};
        System.out.println(numbers[5]); // Throws ArrayIndexOutOfBoundsException
    }
}

🛠 Better Approach: Always check the array length before accessing an index.

if (5 < numbers.length) {
    System.out.println(numbers[5]);
} else {
    System.out.println("Index out of bounds!");
}

3. Differences Between Checked and Unchecked Exceptions

FeatureChecked ExceptionUnchecked Exception
Inherits fromException (but NOT RuntimeException)RuntimeException
Compile-time enforcement✅ Must be handled (try-catch or throws)❌ Not enforced by compiler
Caused byExternal problems (files, DB, network)Programming mistakes (null, invalid index)
Should be handled?✅ Yes (use try-catch or throws)🚫 No (should be prevented by better coding)
ExamplesIOException, SQLException, FileNotFoundExceptionNullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException

4. When to Use Checked vs. Unchecked Exceptions?

Use Checked Exceptions if:

  • The problem is recoverable (like file or network failures).
  • You expect the caller to handle the exception properly.

Use Unchecked Exceptions if:

  • The issue is a coding mistake (like accessing a null reference).
  • The programmer should fix the bug instead of handling it at runtime.

5. Custom Exceptions

You can create your own exceptions by extending Exception (for checked) or RuntimeException (for unchecked).

Custom Checked Exception

class CustomCheckedException extends Exception {
    public CustomCheckedException(String message) {
        super(message);
    }
}

public class CustomExceptionExample {
    public static void validateAge(int age) throws CustomCheckedException {
        if (age < 18) {
            throw new CustomCheckedException("Age must be at least 18");
        }
    }

    public static void main(String[] args) {
        try {
            validateAge(16);
        } catch (CustomCheckedException e) {
            System.out.println("Caught: " + e.getMessage());
        }
    }
}

Custom Unchecked Exception

class CustomUncheckedException extends RuntimeException {
    public CustomUncheckedException(String message) {
        super(message);
    }
}

public class CustomRuntimeExceptionExample {
    public static void validateNumber(int num) {
        if (num < 0) {
            throw new CustomUncheckedException("Number cannot be negative");
        }
    }

    public static void main(String[] args) {
        validateNumber(-5); // No try-catch needed, but will crash if not prevented
    }
}

Final Thoughts

Checked exceptions should be handled because they are expected failures (file I/O, network issues).
Unchecked exceptions should be avoided by writing better code (null checks, proper indexing).
Errors (like OutOfMemoryError) should never be caught—they indicate serious system failures.
Use throws for checked exceptions and try-catch for expected failures in your program.

This entry was posted in Без рубрики. Bookmark the permalink.