0
0
Javaprogramming~5 mins

Checked vs unchecked exceptions in Java

Choose your learning style9 modes available
Introduction

Exceptions help programs handle errors. Checked and unchecked exceptions tell us when and how to handle these errors.

When you want to force the programmer to handle possible errors, like file not found.
When errors are caused by programmer mistakes, like dividing by zero.
When you want to separate recoverable errors from programming bugs.
When designing methods that might fail due to external reasons, like network issues.
Syntax
Java
try {
    // code that might throw exceptions
} catch (ExceptionType e) {
    // handle exception
}

Checked exceptions must be declared or caught.

Unchecked exceptions do not need to be declared or caught.

Examples
Checked exception example: IOException must be declared or handled.
Java
public void readFile() throws IOException {
    // code that might throw IOException
}
Unchecked exception example: ArithmeticException is not declared or caught.
Java
int divide(int a, int b) {
    return a / b; // might throw ArithmeticException
}
Sample Program

This program shows a checked exception (IOException) that must be caught or declared, and an unchecked exception (ArithmeticException) that can be caught but does not have to be declared.

Java
import java.io.*;

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

        try {
            int result = divide(10, 0);
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Caught unchecked exception: " + e.getMessage());
        }
    }

    public static void readFile() throws IOException {
        throw new IOException("File not found");
    }

    public static int divide(int a, int b) {
        return a / b; // might throw ArithmeticException
    }
}
OutputSuccess
Important Notes

Checked exceptions are checked by the compiler at compile time.

Unchecked exceptions are subclasses of RuntimeException and are checked at runtime.

Use checked exceptions for recoverable conditions, unchecked for programming errors.

Summary

Checked exceptions must be declared or handled.

Unchecked exceptions do not require declaration or handling.

Checked exceptions are for recoverable errors; unchecked are for bugs.