Java.Core.What types of exceptions in Java do you know, how do they differ?

Types of Exceptions in Java & Their Differences

In Java, exceptions are categorized based on their recoverability and handling requirements. The main types are:

  1. Checked Exceptions (Compile-time exceptions)
  2. Unchecked Exceptions (Runtime exceptions)
  3. Errors (Serious system-level issues)

1. Checked Exceptions (Must Be Handled)

Definition:
Checked exceptions are forced by the compiler to be either caught (try-catch) or declared (throws) in the method signature. They represent expected failures that a programmer should handle.

Characteristics:

  • Occur due to external factors (files, databases, network, etc.).
  • Must be handled (otherwise, the code won’t compile).
  • Extends Exception (but not RuntimeException).

Examples:

ExceptionWhen It Occurs
IOExceptionFile or network issues
FileNotFoundExceptionFile is missing
SQLExceptionDatabase errors
InterruptedExceptionThread is interrupted
ClassNotFoundExceptionClass is not found at runtime

Example: Handling Checked Exceptions

import java.io.*;

public class CheckedExceptionExample {
    public static void main(String[] args) {
        try {
            FileReader file = new FileReader("test.txt"); // May throw FileNotFoundException
        } catch (FileNotFoundException e) {
            System.out.println("File not found: " + 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.

🚀 Characteristics:

  • Caused by logic errors in the program.
  • Extends RuntimeException.
  • No need for try-catch, but should be prevented with better coding.

🚀 Examples:

ExceptionWhen It Occurs
NullPointerExceptionAccessing a null reference
ArrayIndexOutOfBoundsExceptionAccessing an invalid array index
ArithmeticExceptionDivision by zero
IllegalArgumentExceptionPassing invalid method arguments
ClassCastExceptionIncorrect object casting

🚀 Example: Unchecked Exception

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

🛠 How to prevent?
✅ Use if checks before accessing objects:

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

3. Errors (System-Level Failures)

💀 Definition:
Errors are serious JVM-level failures that should not be caught in the program.

💀 Characteristics:

  • Caused by system failures (memory issues, JVM errors).
  • Extends Error (not Exception).
  • Should NOT be handled—indicates fatal conditions.

💀 Examples:

ErrorWhen It Occurs
StackOverflowErrorInfinite recursion
OutOfMemoryErrorJVM runs out of memory
VirtualMachineErrorJVM crashes
AssertionErrorFailed assert statement

💀 Example: StackOverflowError (Infinite Recursion)

public class StackOverflowExample {
    public static void recursiveMethod() {
        recursiveMethod(); // Infinite recursion!
    }

    public static void main(String[] args) {
        recursiveMethod(); // Causes StackOverflowError
    }
}

⚠️ Solution: Avoid infinite recursion by adding a base case.


4. Summary Table

TypeInheritsCompiler Forces Handling?When to Use
Checked ExceptionException✅ YesHandle recoverable failures (I/O, DB, network)
Unchecked ExceptionRuntimeException❌ NoFix logic errors in code (null access, bad indexing)
ErrorError🚫 NoJVM-level failures (out of memory, recursion)

5. Custom Exception Example

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

Custom Checked Exception

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

public class CustomExceptionExample {
    public static void main(String[] args) {
        try {
            throw new CustomCheckedException("Custom checked exception occurred");
        } catch (CustomCheckedException e) {
            System.out.println("Handled: " + e.getMessage());
        }
    }
}

Custom Unchecked Exception

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

public class CustomRuntimeExceptionExample {
    public static void main(String[] args) {
        throw new CustomUncheckedException("This is an unchecked exception");
    }
}

Final Thoughts

Use checked exceptions for recoverable failures (I/O, network, DB).
Use unchecked exceptions for programming mistakes (null references, bad indexes).
Errors should not be caught—fix the underlying system issue instead.
Use meaningful exception messages for better debugging.

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