Java provides a robust hierarchy of built-in
exceptions for handling various runtime errors and other conditions. All
exceptions are derived from the Throwable class, which has two main subclasses:
- Exception – Indicates conditions that a reasonable
application might want to catch.
- Error – Indicates serious problems that a reasonable
application should not try to catch (e.g., OutOfMemoryError).
📌 Exception
Hierarchy
Throwable
/ \
Error Exception
/ \
RuntimeException IOException
📌 Categories of
Built-In Exceptions
1. Checked
Exceptions (Compile-Time Exceptions)
These are exceptions that must be handled using try-catch blocks or declared using throws keyword. If not handled, they result in a compilation
error.
🔍 Examples:
- IOException - Signals an I/O operation failure.
- SQLException - Database access error.
- ClassNotFoundException - When a
specified class cannot be found.
- FileNotFoundException - Attempt
to access a non-existent file.
- InterruptedException - Occurs
when a thread is interrupted.
2. Unchecked
Exceptions (Runtime Exceptions)
These exceptions occur during runtime and are not
checked at compile-time. They result from programming errors such as logic
flaws or improper API usage.
🔍 Examples:
- ArithmeticException - Division
by zero.
- NullPointerException - Attempt
to access an object with a null reference.
- ArrayIndexOutOfBoundsException - Accessing
an invalid array index.
- NumberFormatException - Invalid
conversion of a string to a numeric type.
- IllegalArgumentException - Method
has been passed an illegal or inappropriate argument.
3. Errors (Severe
Problems)
These represent serious errors that are generally
not caught by applications. They are meant to signal conditions from which
recovery is not possible.
🔍 Examples:
- OutOfMemoryError - JVM runs
out of memory.
- StackOverflowError - Excessive
recursion resulting in stack exhaustion.
- VirtualMachineError - Internal
JVM errors or resource exhaustion.
- AssertionError - Assertion
failure during runtime.
📌 Common Built-In
Exceptions and Descriptions
Exception |
Description |
ArithmeticException |
Thrown when an illegal arithmetic operation occurs, like division by
zero. |
ArrayIndexOutOfBoundsException |
Thrown when accessing an array with an invalid index. |
ClassNotFoundException |
Thrown when trying to load a class that doesn't exist. |
FileNotFoundException |
Thrown when a file with the specified pathname does not exist. |
IOException |
General I/O exception when working with streams. |
NullPointerException |
Thrown when attempting to access or modify an object reference that is
null. |
NumberFormatException |
Thrown when a method cannot convert a string into a numeric format. |
IllegalArgumentException |
Thrown when a method receives an argument that is inappropriate. |
IllegalStateException |
Thrown when a method is invoked at an inappropriate time. |
IndexOutOfBoundsException |
Thrown when trying to access an invalid index of a list, string, or
array. |
NoSuchElementException |
Thrown when one tries to access an element not present. |
SecurityException |
Thrown when a security manager detects a security violation. |
UnsupportedOperationException |
Thrown when an unsupported operation is attempted. |
StackOverflowError |
Thrown when the stack memory limit is exceeded, often due to recursive
calls. |
OutOfMemoryError |
Thrown when the JVM runs out of memory. |
📌 Example
Demonstrating Various Built-In Exceptions
public class
BuiltInExceptionsDemo {
public static void main(String[] args) {
// 1. ArithmeticException
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("ArithmeticException caught: " +
e.getMessage());
}
// 2. NullPointerException
try {
String str = null;
System.out.println(str.length());
} catch (NullPointerException e) {
System.out.println("NullPointerException caught: " +
e.getMessage());
}
// 3. ArrayIndexOutOfBoundsException
try {
int[] arr = new int[5];
System.out.println(arr[10]);
} catch (ArrayIndexOutOfBoundsException
e) {
System.out.println("ArrayIndexOutOfBoundsException caught: " +
e.getMessage());
}
// 4. NumberFormatException
try {
int number =
Integer.parseInt("abc");
} catch (NumberFormatException e) {
System.out.println("NumberFormatException caught: " +
e.getMessage());
}
// 5. FileNotFoundException (Checked
Exception)
try {
java.io.FileReader reader = new
java.io.FileReader("nonexistentfile.txt");
} catch (java.io.FileNotFoundException
e) {
System.out.println("FileNotFoundException caught: " +
e.getMessage());
}
}
}
📌 Output:
ArithmeticException
caught: / by zero
NullPointerException
caught: Cannot invoke "String.length()" because "str" is
null
ArrayIndexOutOfBoundsException
caught: Index 10 out of bounds for length 5
NumberFormatException
caught: For input string: "abc"
FileNotFoundException
caught: nonexistentfile.txt (No such file or directory)
📌 Key Points to
Remember:
- Exception class and its
subclasses are meant to be caught and handled by the programmer.
- Error class and its
subclasses are not intended to be caught by the programmer.
- Exception handling enhances program reliability and robustness.
- Exceptions can be handled by using try-catch-finally blocks or using the throws keyword.
No comments:
Post a Comment