Java Programming Handbook

    Checked and Unchecked Exceptions in Java

    Introduction#

    In Java, exceptions are categorized into two types:

    1. Checked Exceptions – Exceptions that must be handled at compile time.
    2. Unchecked Exceptions – Exceptions that occur at runtime and do not require mandatory handling.

    In this blog, we will discuss:

    • The difference between checked and unchecked exceptions
    • Common examples of both
    • How to handle them properly
    • Best practices for using exceptions in Java

    What are Checked Exceptions?#

    Checked exceptions are exceptions that must be handled using a try-catch block or declared using throws in the method signature. If not handled, the compiler will throw an error.

    Examples of Checked Exceptions:#

    • IOException
    • SQLException
    • FileNotFoundException
    • ClassNotFoundException
    • InterruptedException

    Example of Checked Exception:#

    import java.io.File; import java.io.FileReader; import java.io.IOException; public class CheckedExceptionExample { public static void main(String[] args) { try { File file = new File("test.txt"); FileReader fr = new FileReader(file); // This may throw FileNotFoundException } catch (IOException e) { System.out.println("Exception caught: " + e.getMessage()); } } }

    Output:#

    Exception caught: test.txt (No such file or directory)

    Explanation: Since reading a file is an external operation, Java forces us to handle IOException to avoid crashes.

    What are Unchecked Exceptions?#

    Unchecked exceptions are runtime exceptions that occur due to programming errors. They are not checked at compile time, meaning the developer is responsible for handling them.

    Examples of Unchecked Exceptions:#

    • NullPointerException
    • ArrayIndexOutOfBoundsException
    • ArithmeticException
    • NumberFormatException
    • IllegalArgumentException

    Example of Unchecked Exception:#

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

    Output:#

    Exception in thread "main" java.lang.ArithmeticException: / by zero at UncheckedExceptionExample.main(UncheckedExceptionExample.java:4)

    Explanation: Dividing by zero is an invalid operation, leading to an ArithmeticException at runtime.

    Key Differences Between Checked and Unchecked Exceptions#

    FeatureChecked ExceptionUnchecked Exception
    Checked at Compile Time✅ Yes❌ No
    Must be Handled✅ Yes❌ No
    ExtendsException (but NOT RuntimeException)RuntimeException
    ExampleIOException, SQLExceptionNullPointerException, ArithmeticException
    Occurs Due toExternal factors (e.g., file missing, database connection error)Programming mistakes (e.g., null references, division by zero)

    How to Handle Checked and Unchecked Exceptions#

    Handling Checked Exceptions:#

    Checked exceptions must be handled using try-catch or declared with throws.

    import java.io.IOException; public class CheckedHandlingExample { public static void main(String[] args) { try { throw new IOException("File not found"); } catch (IOException e) { System.out.println("Handled checked exception: " + e.getMessage()); } } }

    Handling Unchecked Exceptions:#

    Unchecked exceptions should be prevented through proper coding practices. However, you can use try-catch if needed.

    public class UncheckedHandlingExample { public static void main(String[] args) { try { String str = null; System.out.println(str.length()); // Will throw NullPointerException } catch (NullPointerException e) { System.out.println("Handled unchecked exception: " + e.getMessage()); } } }

    Best Practices for Using Exceptions#

    • Use checked exceptions for recoverable conditions (e.g., missing files, invalid input).
    • Use unchecked exceptions for programming logic errors (e.g., null values, division by zero).
    • Avoid unnecessary exception handling – only catch exceptions when you can recover from them.
    • Use meaningful exception messages to help debug issues quickly.
    • Always close resources properly (use try-with-resources for handling resources like files, sockets, etc.).

    Conclusion#

    In this blog, we covered:

    • What checked and unchecked exceptions are
    • Examples of each with real-world scenarios
    • How to handle them effectively
    • Best practices for working with exceptions

    Next, we will explore Throw vs Throws in Java, where we’ll see how to explicitly throw exceptions and declare them in method signatures.

    Last updated on Apr 09, 2025