JAVA - Zero to Hero / Exception Handling

Types of Exceptions

Types of Exceptions

💡What are Exception Types?

In Java, exceptions are categorized based on when they’re detected and how they’re handled.

There are two main types:

  1. Checked Exceptions

  2. Unchecked Exceptions

✔️ Checked Exceptions

These are exceptions that the compiler checks at compile-time.

If your code might throw one of these, Java forces you to either:

  • Handle it using try-catch, or

  • Declare it using throws

🔧 Examples of Checked Exceptions:

Exception

Description

IOException

File not found, read/write failure

SQLException

Database connection error

FileNotFoundException

File doesn’t exist

InterruptedException

Thread interruption issues

🔸 Example:

(*We will study about this in further modules)

import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        FileReader file = new FileReader("data.txt");  // File might not exist
        file.close();
    }
}
Exception in thread "main" java.io.FileNotFoundException: data.txt (No such file or directory)

⚠️ Unchecked Exceptions

  • These occur at runtime and are not checked by the compiler.

  • You’re not forced to handle them — but you should, to avoid crashes.

🔧 Examples of Unchecked Exceptions:

Exception

Description

ArithmeticException

Divide by zero

NullPointerException

Accessing method on null object

ArrayIndexOutOfBoundsException

Invalid index access in array

NumberFormatException

Parsing invalid number from string

🔸 Example:

public class Main {
    public static void main(String[] args) {
        int[] nums = {1, 2, 3};
        System.out.println(nums[5]);  // Index out of range
    }
}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds

🧠 Error Class (Bonus: Not an Exception)

Java also has a separate branch under Throwable called Error — these are system-level failures (like memory issues).

Example

Description

OutOfMemoryError

JVM runs out of memory

StackOverflowError

Infinite recursion

**These are usually not handled with try-catch.

✅ Are There Any Other Ways to Handle Errors?

Yes — in very rare or critical systems, developers might try to:

🛡️ 1. Catch them cautiously:

try {
    // risky code (like recursion)
} catch (StackOverflowError e) {
    System.out.println("Stack overflow occurred!");
}

⚠️ Use this only when you must do logging, emergency cleanup, or crash reporting.


🧼 2. Use finally for cleanup:

Even if an error occurs, the finally block still runs:

try {
    // risk of OutOfMemoryError
} finally {
    System.out.println("Cleaning up resources...");
}

🧠 3. Prevent them proactively:

  • Avoid infinite recursion to prevent StackOverflowError.

  • Use efficient data structures and close unused objects to avoid OutOfMemoryError.

  • Tune JVM memory limits (using Xmx flags) in large applications.

🧾 Recap Table

Type

Compiler Checked?

When Occurs

Examples

Checked Exception

✅ Yes

Compile Time

IOException, SQLException

Unchecked Exception

❌ No

Runtime

NullPointerException, ArithmeticException

Errors

❌ No

Runtime (fatal)

OutOfMemoryError, StackOverflowError