πŸ”· Exception

An exception is an unexpected event that occurs during the execution of a program, which disrupts the normal flow of instructions.

Exceptions are objects that represent errors.

πŸ“Š Java Exception Hierarchy


java.lang.Object
 └── java.lang.Throwable
     β”œβ”€β”€ java.lang.Error (Serious problems)
     └── java.lang.Exception (Recoverable problems)
         β”œβ”€β”€ Checked Exceptions
         └── Unchecked Exceptions (RuntimeException and its subclasses)

        

πŸ”· 1. Checked Exceptions (Compile-time)

These must be handled using try-catch or declared with throws

βœ… Examples :

  • IOException
  • SQLException
  • FileNotFoundException
  • ClassNotFoundException

πŸ“ Examples :

					 
import java.io.*;
public class FileRead {
    public static void main(String[] args) throws IOException {
        FileReader fr = new FileReader("test.txt"); // must handle or declare
        int i;
        while ((i = fr.read()) != -1)
            System.out.print((char) i);
        fr.close();
    }
}
						
					

πŸ”· 2. Unchecked Exceptions (Runtime)

These don't need to be handled explicitly They are subclasses of RuntimeException.

βœ… Examples :

  • NullPointerException
  • ArrayIndexOutOfBoundsException
  • ArithmeticException
  • IllegalArgumentException

πŸ“ Examples :

					
public class Divide {
    public static void main(String[] args) {
        int a = 10 / 0; // ArithmeticException
    }
}

        

πŸ”· 3. Errors (System-related)

These are not meant to be handled by the program β€” usually related to the environment

βœ… Examples :

  • StackOverflowError
  • OutOfMemoryError
  • VirtualMachineError

🎯 Exception Handling Keywords

πŸ”§ Keywords:
Keyword Description
try Wrap code that might throw an exception
catch Handle the exception
finally Block that runs regardless of exception
throw Manually throw an exception
throws Declare exceptions a method can throw

πŸ“ Example: try-catch-finally

					
public class TryCatchExample {
    public static void main(String[] args) {
        try {
            int result = 10 / 0;
        } catch (ArithmeticException e) {
            System.out.println("Error: Division by zero.");
        } finally {
            System.out.println("This block always runs.");
        }
    }
}

        

🎯 Creating Custom Exceptions

You can create your own exception by extending Exception or RuntimeException

πŸ“ Example:

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

public class Custom {
    public static void main(String[] args) throws MyException {
        throw new MyException("This is a custom exception!");
    }
}

        

πŸ“Œ Common Exception Types

Exception Type When it Occurs
NullPointerException Unchecked Accessing object with null reference
ArrayIndexOutOfBounds Unchecked Invalid array index
NumberFormatException Unchecked Invalid conversion of String to number
IOException Checked Input/output failure
ClassNotFoundException Checked Class not found at runtime
FileNotFoundException Checked File does not exist
ArithmeticException Unchecked Divide by zero

πŸ“ Best Practices

  • Catch specific exceptions.
  • Use finally to close resources (or use try-with-resources).
  • Don’t catch Exception or Throwable blindly.
  • Use custom exceptions for meaningful error reporting.

βœ… Checked vs. Unchecked Exceptions in Java

Feature Checked Exception Unchecked Exception
Inheritance Subclass of Exception (but not RuntimeException) Subclass of RuntimeException
Compile-time Checking βœ… Checked at compile-time ❌ Not Checked at compile-time
Must Handle or Declare βœ… Yes β€” must be handled with try-catch or throws ❌ No β€” optional to handle
Common Examples IOException, SQLException,FileNotFoundException NullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException
Use Case External factors (e.g., file, network, DB Programming errors (e.g., null reference)
When to Use When the program can recover from the exception When the program cannot recover or it's a bug

πŸ“ Code Examples

πŸ”· Checked Exception β€” must be handled

					
import java.io.*;
public class CheckedExample {
 public static void main(String[] args) {
 try {
 FileReader fr = new FileReader("file.txt"); // 
FileNotFoundException (checked)
} catch (FileNotFoundException e) {
 System.out.println("File not found!");
 }
 }
 
				

If you don’t handle or declare this exception, the compiler will throw an error.

πŸ”· Unchecked Exception β€” optional to handle

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

				

This compiles fine , but crashes at runtime.

βœ… Difference Between throw vs throws

Feature throw throws
Purpose Used to actually throw an exception Used to declare an exception might be thrown
Position Used Inside a method Used in the method signature
Followed By An exception object One or more exception classes
Number Can only throw one exception at a time an declare multiple exceptions (commaseparated)
Checked/ Unchecked Works for both types Required only for checked exceptions

πŸ”· throw - Actually throws the exception

πŸ“ Syntax :

throw new ExceptionType("error message");

βœ… Example :

					
public class ThrowExample {
    public static void main(String[] args) {
        throw new ArithmeticException("Can't divide by zero");
    }
}

        

Here, the program immediately stops when the exception is thrown.

πŸ”· throws - Declares the possibility of an exception

πŸ“ Syntax :

returnType methodName() throws ExceptionType1, ExceptionType2

βœ… Example :

					
public void readFile() throws IOException {
 FileReader file = new FileReader("test.txt"); // Might 
throw IOException
}

        

This tells the compiler and caller that readFile() might throw IOException , so it must be handled there.

πŸ”„ Summary:

Keyword Used to... Followed by... Used where?
throw Actually throw Object of exception class Inside method/block
throws Declare an exception Exception class name(s) Method signature