π· 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
orThrowable
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 |