Difference between Checked and Unchecked Exception

Checked Exception:

Checked exceptions are a concept in Java (and some other programming languages) used to handle exceptional conditions that may arise during the execution of a program. Unlike unchecked exceptions (runtime exceptions), checked exceptions must be explicitly handled by the programmer, either by using a try-catch block or by declaring them in the method signature using the throws keyword.Some Checked Exceptions in Java are : IOException, FileNotFoundException, SQLException, ParseException, ClassNotFoundException, etc.

There are two types of keywords for Checked Exception :

1) throws 

2) try-catch block 

throws : In Java, the throws keyword is used in method declarations to indicate that the method may throw a specific exception during its execution. When a method declares that it throws an exception using the throws keyword, it is essentially stating that it will not handle the exception within the method and will instead propagate it to the calling method or the JVM.

throws keyword syntax:

returnType methodName(parameters) throws ExceptionType1, ExceptionType2, ... {
    // method body
}
throws keyword code example:
import java.io.*;

public class FileReadExample {
    // Method that declares it may throw an IOException
    public static void readFile() throws IOException {
        BufferedReader br = new BufferedReader(new FileReader("example.txt"));
        // Code to read from the file...
        br.close();
    }

    // Method that calls readFile() and handles the IOException
    public static void main(String[] args) {
        try {
            readFile();
        } catch (IOException e) {
            // Handle the IOException here
            e.printStackTrace();
        }
    }
}
try-catch : The try-catch block is a fundamental construct in Java used for exception handling. It allows you to gracefully handle exceptions that might occur during the execution of a block of code. By using the try-catch block, you can separate the code that might throw an exception from the code that handles the exception, promoting more robust and reliable programs.

try-catch keyword syntax:
try {
    // Code that might throw an exception
} catch (ExceptionType1 e1) {
    // Code to handle ExceptionType1
} catch (ExceptionType2 e2) {
    // Code to handle ExceptionType2
} finally {
    // Optional: Code that always executes, whether there's an exception or not
}
try catch keyword code example:
public class ExceptionExample {
    public static void main(String[] args) {
        try {
            int result = divide(10, 0); // This method may throw an ArithmeticException
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.err.println("Exception occurred: " + e.getMessage());
        } finally {
            System.out.println("Finally block executed");
        }
    }

    public static int divide(int dividend, int divisor) {
        return dividend / divisor; // This line may throw ArithmeticException if divisor is 0
    }
}
Unchecked Exception:

Unchecked exceptions, also known as runtime exceptions, are a type of exception in Java that do not need to be explicitly handled using try-catch blocks or declared with the throws keyword. Unlike checked exceptions, which are enforced by the compiler, unchecked exceptions are not checked at compile time, making them less restrictive in terms of error handling.Some UnChecked Exceptions in Java are : NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException, IllegalArgumentException, ClassCastException, and IndexOutOfBoundsException etc.

Unchecked Exception code example:
public class UncheckedExample {
    public static void main(String[] args) {
        int a = 10;
        int b = 0;
        int result = a / b; // This line will throw an ArithmeticException (division by zero)
        System.out.println("Result: " + result);
    }   
}
Difference between Checked and Unchecked Exception:

Checked Exception:

1. Must be explicitly handled using try-catch blocks or declared with throws.
2. Checked at compile time.
3. Represents expected exceptional conditions that can be recovered from.
4. Forces programmers to handle potential errors.

Unchecked Exception :

1. Not required to be explicitly handled or declared.
2. Not checked at compile time.
3. Represents unexpected programming errors or conditions beyond programmer's control.
4. Provides flexibility but requires careful handling to prevent unexpected program behavior.
Next Post Previous Post