In Java, an exception is an event that
disrupts the normal flow of execution in a program. Exceptions occur during
runtime due to various reasons like invalid input, hardware failure, or logical
errors in code.
Exception
Hierarchy in Java
The root class of all exceptions in Java is Throwable, which is a subclass of Object. It has two
direct subclasses:
- Exception (java.lang.Exception) – Used for handling conditions that a program
should catch and handle.
- Error (java.lang.Error) – Represents serious system failures that a
program should not attempt to catch (e.g., OutOfMemoryError).
Java Exception
Hierarchy Diagram
Object
│
Throwable
│
┌──────────┴───────────┐
│ │
Error Exception
│ │
│ ┌────────┴──────────┐
(System-related) IOException RuntimeException
│ │
FileNotFoundException ArithmeticException
EOFException NullPointerException
etc.
ArrayIndexOutOfBoundsException
etc.
Types of
Exceptions in Java
1. Checked
Exceptions (Compile-time Exceptions)
- These exceptions are checked at compile time.
- The compiler forces the programmer to handle them using try-catch
or throws.
- Example: IOException, SQLException, FileNotFoundException.
import java.io.*;
public class
CheckedExceptionExample {
public static void main(String[] args) {
try {
FileReader file = new
FileReader("non_existent_file.txt");
BufferedReader br = new
BufferedReader(file);
} catch (IOException e) {
System.out.println("File not
found: " + e.getMessage());
}
}
}
2. Unchecked
Exceptions (Runtime Exceptions)
- These exceptions occur at runtime and are not checked at compile time.
- They occur due to programming logic errors, such as division by zero
or accessing an invalid index.
- Example: NullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException.
public class
UncheckedExceptionExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3};
System.out.println(numbers[5]); // ArrayIndexOutOfBoundsException
}
}
3. Errors
(Serious System Failures)
- Errors are serious failures that usually cannot be handled in a normal
program.
- Example: OutOfMemoryError, StackOverflowError.
public class
ErrorExample {
public static void recursiveMethod() {
recursiveMethod(); // Infinite recursion leading to
StackOverflowError
}
public static void main(String[] args) {
recursiveMethod();
}
}
No comments:
Post a Comment