Explain inbuilt and user defined, checked and unchecked exceptions with example.

Java Exceptions: Inbuilt vs User-Defined, Checked vs Unchecked (with Examples)

In Java, an exception is an event that disrupts the normal flow of a program. Exception handling lets you detect errors, handle them gracefully, and keep your application stable. Understanding inbuilt and user-defined exceptions, as well as checked and unchecked exceptions, is essential for clean, reliable Java code.

Inbuilt (Built-in) Exceptions

Inbuilt exceptions are provided by the Java API. They cover common error scenarios and are ready to use.

  • Checked (compile-time) inbuilt exceptions: IOException, FileNotFoundException, SQLException, ClassNotFoundException
  • Unchecked (runtime) inbuilt exceptions: NullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException, NumberFormatException

Example: Inbuilt Checked Exception (IOException)

// Demonstrates handling built-in checked exceptions
import java.io.*;

class ReadFileDemo {
    public static void main(String[] args) {
        try (BufferedReader br = new BufferedReader(new FileReader("data.txt"))) {
            System.out.println("First line: " + br.readLine());
        } catch (FileNotFoundException e) {
            System.out.println("File not found: " + e.getMessage());
        } catch (IOException e) {
            System.out.println("I/O error: " + e.getMessage());
        }
    }
}

Example: Inbuilt Unchecked Exception (ArithmeticException)

// Demonstrates an unchecked exception at runtime
class UncheckedDemo {
    public static void main(String[] args) {
        int a = 10, b = 0;
        // No compile-time error, but at runtime this throws ArithmeticException
        int c = a / b;
        System.out.println(c);
    }
}

User-Defined (Custom) Exceptions

User-defined exceptions are custom classes you create to represent application-specific error conditions. They improve readability and make error handling meaningful.

  • Create a checked custom exception by extending Exception.
  • Create an unchecked custom exception by extending RuntimeException.

Example: Custom Checked and Unchecked Exceptions

// Custom checked exception (must be handled or declared)
class AgeNotValidException extends Exception {
    public AgeNotValidException(String message) {
        super(message);
    }
}

class VoterService {
    void register(int age) throws AgeNotValidException {
        if (age < 18) {
            throw new AgeNotValidException("Age must be 18 or above for registration.");
        }
        System.out.println("Registration successful!");
    }

    public static void main(String[] args) {
        VoterService service = new VoterService();
        try {
            service.register(16); // will throw the checked exception
        } catch (AgeNotValidException e) {
            System.out.println("Registration failed: " + e.getMessage());
        }
    }
}

// Custom unchecked exception (optional to handle)
class InvalidMarksException extends RuntimeException {
    public InvalidMarksException(String message) {
        super(message);
    }
}

class MarksService {
    int grade(int marks) {
        if (marks < 0 || marks > 100) {
            throw new InvalidMarksException("Marks must be between 0 and 100.");
        }
        return (marks >= 40) ? 1 : 0; // 1: Pass, 0: Fail
    }

    public static void main(String[] args) {
        MarksService ms = new MarksService();
        // This will throw at runtime because 120 is invalid
        System.out.println("Grade: " + ms.grade(120));
    }
}

Checked vs Unchecked Exceptions (Key Differences)

  • When detected:
    • Checked: Verified at compile time.
    • Unchecked: Occur at runtime.
  • Handling rule:
    • Checked: Must be caught (try-catch) or declared (throws).
    • Unchecked: Handling is optional but recommended when recoverable.
  • Class hierarchy:
    • Checked: Subclasses of Exception (excluding RuntimeException).
    • Unchecked: Subclasses of RuntimeException.
  • Typical causes:
    • Checked: External issues (I/O, database, network).
    • Unchecked: Programming errors (null access, bad index, divide by zero).

Keywords You Will Use

  • try-catch: Surrounds risky code and handles exceptions.
  • finally: Runs cleanup code (always executes, except in rare cases like System.exit).
  • throw: Actively throws an exception.
  • throws: Declares that a method can throw specified exceptions.

Best Practices

  • Use specific exception types; avoid catching Exception broadly unless necessary.
  • For recoverable, external errors, prefer checked exceptions.
  • For programming errors (invalid state or arguments), prefer unchecked exceptions.
  • Provide clear, actionable messages in exceptions.
  • Log exceptions and release resources (use try-with-resources or finally).

Quick Recap

  • Inbuilt exceptions come from the JDK; user-defined exceptions are custom classes you create.
  • Checked exceptions must be handled or declared; unchecked exceptions are optional to handle.
  • Create custom checked exceptions by extending Exception; unchecked by extending RuntimeException.