✅ Exceptions and Exception
Hierarchy in Java
📌 What are
Exceptions?
An exception is an event that disrupts the
normal flow of a program during execution. In Java, exceptions are objects that
describe an error or unexpected behavior occurring during runtime.
📌 Why Use
Exceptions?
- Improved Code Readability: Handles
errors using separate code blocks.
- Separation of Error Handling Code: Keeps the
main logic clean.
- Controlled Error Handling: Allows the
program to gracefully recover from unexpected events.
📌 Exception
Hierarchy in Java
All exceptions in Java are subclasses of the Throwable class, which is the superclass for all errors and exceptions.
🔍 Structure:
Throwable
/ \
Error Exception
/ \
Checked Exceptions Unchecked Exceptions
(RuntimeException)
📌 Types of
Exceptions
1. Checked
Exceptions (Compile-time Exceptions)
These exceptions are checked at compile time. If not
handled, the compiler will throw an error.
Examples:
- IOException
- SQLException
- ClassNotFoundException
Example Code:
import java.io.*;
public class
CheckedExample {
public static void main(String[] args) {
try {
FileInputStream file = new
FileInputStream("nonexistentfile.txt");
} catch (FileNotFoundException e) {
System.out.println("File not
found exception caught!");
}
}
}
2. Unchecked
Exceptions (Runtime Exceptions)
These exceptions occur at runtime and are not
checked during compilation.
Examples:
- NullPointerException
- ArrayIndexOutOfBoundsException
- ArithmeticException
Example Code:
public class
UncheckedExample {
public static void main(String[] args) {
int[] arr = new int[3];
try {
System.out.println(arr[5]); //
ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException
e) {
System.out.println("Array
index out of bounds exception caught!");
}
}
}
3. Errors
Errors are severe issues that a program usually
cannot recover from.
Examples:
- OutOfMemoryError
- StackOverflowError
- VirtualMachineError
Example Code:
public class
ErrorExample {
public static void recursiveMethod() {
recursiveMethod(); // Infinite recursion causing
StackOverflowError
}
public static void main(String[] args) {
recursiveMethod();
}
}
📌 Exception Class
Hierarchy (Important Classes)
- Throwable (Superclass for all exceptions and errors)
- Exception (General superclass for recoverable exceptions)
- Checked Exceptions (Require handling)
- IOException
- SQLException
- FileNotFoundException
- Unchecked Exceptions (RuntimeExceptions, not compulsory to handle)
- ArithmeticException
- NullPointerException
- IndexOutOfBoundsException
- Error (Serious problems not meant to be caught by applications)
- OutOfMemoryError
- StackOverflowError
- VirtualMachineError
📌 Common Exception
Methods
public String
getMessage() // Returns detailed
message about the exception.
public String
toString() // Returns a short
description of the exception.
public void
printStackTrace() // Prints the stack
trace to the console.
📌 Creating a
Custom Exception
class
CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
public class
CustomExceptionDemo {
public static void main(String[] args) {
try {
throw new
CustomException("This is a custom exception!");
} catch (CustomException e) {
System.out.println(e.getMessage());
}
}
}
📌 Key Points to
Remember
- Checked Exceptions: Must be
handled using try-catch or declared
using throws.
- Unchecked Exceptions: Can be
handled, but not mandatory.
- Errors: Critical issues; typically not caught by the
application.
- Custom Exceptions: Useful for
specific error handling in your application.
No comments:
Post a Comment