Exception in Java

⚠️ What is an Exception in Java?

An Exception is an unexpected event that occurs during the execution of a program and disrupts its normal flow.

🔥 It represents runtime errors like division by zero, file not found, or null reference access.


🔧 Types of Exceptions:

1. Checked Exceptions

  • Checked at compile time
  • Must be handled using try-catch or declared with throws

✅ Examples:

  • IOException
  • SQLException
  • FileNotFoundException
try {
    FileReader file = new FileReader("abc.txt");
} catch (FileNotFoundException e) {
    System.out.println("File not found!");
}


2. Unchecked Exceptions

  • Checked at runtime
  • Caused by programming errors
  • Not required to handle explicitly

✅ Examples:

  • NullPointerException
  • ArithmeticException
  • ArrayIndexOutOfBoundsException
int x = 10 / 0; // ArithmeticException

3. Errors (Not Exceptions technically)

  • Serious problems that cannot be handled by the program
  • Example: OutOfMemoryError, StackOverflowError

🚧 Exception Hierarchy:

Throwable
├── Error (not meant to catch)
└── Exception
    ├── Checked Exceptions (e.g., IOException)
    └── Unchecked Exceptions (RuntimeException and its subclasses)

🔁 Handling Exceptions:

try-catch-finally block:

try {
    int a = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero!");
} finally {
    System.out.println("Cleanup done.");
}

throws keyword:

public void readFile() throws IOException {
    FileReader fr = new FileReader("abc.txt");
}


✅ Summary:

Feature Description
What is it? Runtime event disrupting normal flow
Types Checked, Unchecked, Errors
Handled using try-catch, throws, finally
Common examples NullPointerException, IOException, ArrayIndexOutOfBoundsException

 

☄️ throw vs throws – Key Difference

Keyword Purpose Used For Position in Code
throw Actually throws an exception Inside a method/block Inside method body
throws Declares an exception In method signature After method declaration

🔹 throw Keyword

  • Used to explicitly throw an exception (checked or unchecked).
  • Only one exception can be thrown at a time.

✅ Syntax:

throw new ExceptionType("Error message");

🔍 Example:

public class Demo {
    public static void main(String[] args) {
        throw new ArithmeticException("Divide by zero");
    }
}
 

🔸 throws Keyword

  • Used to declare exceptions a method might throw.
  • Compiler checks if checked exceptions are handled or declared.

✅ Syntax:

returnType methodName() throws ExceptionType1, ExceptionType2 { }

🔍 Example:

public void readFile() throws IOException {
    FileReader fr = new FileReader("abc.txt");
}
 

🧠 Example Using Both:

public void checkAge(int age) throws IllegalArgumentException {
    if (age < 18) {
        throw new IllegalArgumentException("Age must be 18 or older");
    }
}
  • throws declares the method might throw IllegalArgumentException
  • throw actually throws the exception if condition fails

✅ Summary:

Feature throw throws
Action Actually throws an exception Declares an exception
Used in Method body Method signature
Exceptions One at a time Multiple can be declared
Purpose Generate an exception manually Inform caller to handle exception

 

⚠️ What are Built-in Exceptions?

Built-in exceptions are predefined classes in Java provided by the JDK to handle common runtime and compile-time errors.

All exceptions extend from the Throwable class.


🧩 Java Exception Hierarchy

Throwable
├── Error (fatal errors)
└── Exception
    ├── Checked Exceptions (compile-time)
    └── Unchecked Exceptions (RuntimeException)

✅ Common Built-in Exceptions

🔷 Checked Exceptions (Compile-time)

Exception Description
IOException I/O failure like file not found
FileNotFoundException File is missing while reading
SQLException Database access errors
ClassNotFoundException Class not found during runtime loading
InterruptedException Thread interrupted during waiting

🔒 Must be handled using try-catch or declared using throws.


🔶 Unchecked Exceptions (Runtime Exceptions)

Exception Description
ArithmeticException Division by zero or other arithmetic errors
NullPointerException Accessing object methods/fields with null
ArrayIndexOutOfBoundsException Accessing invalid array index
NumberFormatException Converting string to number fails
IllegalArgumentException Invalid arguments passed to a method
ClassCastException Invalid object type casting

🔓 No need to handle explicitly, but can cause crashes if ignored.


🔥 Errors (Not usually caught)

Error Description
StackOverflowError Infinite recursion
OutOfMemoryError Heap memory exhausted
NoClassDefFoundError Class not found at runtime

🧪 Example:

public class Example {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3};
        System.out.println(arr[5]); // ArrayIndexOutOfBoundsException
    }
}

✅ Summary:

Category Handled At Examples
Checked Exceptions Compile-time IOException, SQLException
Unchecked Runtime NullPointerException, ArithmeticException
Errors Usually not caught StackOverflowError, OutOfMemoryError

 

🔧 What is a Custom Exception?

A Custom Exception is a user-defined exception class that extends Java's Exception or RuntimeException.

It allows you to create meaningful and specific error messages for your application logic.


✅ When to Use:

  • To handle domain-specific errors
  • To make error handling more readable and maintainable
  • To enforce business rules

🧱 Steps to Create a Custom Exception:

✅ 1. Extend Exception (Checked) or RuntimeException (Unchecked)

🔹 Example: Custom Checked Exception

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

🔸 Example: Custom Unchecked Exception

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

🧪 How to Use in Code

public class TestCustomException {
    static void validateAge(int age) throws AgeValidationException {
        if (age < 18) {
            throw new AgeValidationException("Age must be 18 or older.");
        }
        System.out.println("Age is valid.");
    }

    public static void main(String[] args) {
        try {
            validateAge(16);
        } catch (AgeValidationException e) {
            System.out.println("Exception caught: " + e.getMessage());
        }
    }
}


🔁 Summary Table

Base Class Type When Used
Exception Checked Exception Must be caught or declared with throws
RuntimeException Unchecked Optional to catch, used for programming logic

💡 Tips:

  • Add constructors for flexibility (with or without message)
  • Avoid overusing unchecked exceptions unless truly logical
  • Name your exceptions meaningfully (e.g., InsufficientBalanceException, DataNotFoundException)
Back to blog

Leave a comment

Please note, comments need to be approved before they are published.