What is an Exception?
An exception is an unwanted or unexpected event that occurs during the execution of a program, disrupting the normal flow of instructions.
Example:
- Dividing a number by zero
- Accessing an invalid array index
- Trying to open a file that doesn’t exist
Exception Hierarchy in Java
In Java, all exceptions are part of a class hierarchy.
Object
└── Throwable
├── Exception
│ ├── Checked Exceptions
│ └── Unchecked Exceptions (RuntimeException)
└── Error
Important Concept:
Every exception class in Java is either a direct or indirect child of the Exception class (except Error, which represents serious system issues).
## Try-Catch Block
The `try-catch` block is used to handle exceptions.
### Syntax:
java
try {
// Code that may cause exception
} catch (ExceptionType e) {
// Code to handle exception
}
Example:
public class Test {
public static void main(String[] args) {
try {
int result = 10 / 0; // risky code
} catch (Arithmetic Exception e) {
System.out.println("Cannot divide by zero!");
}
}
}
Multiple Catch Blocks
You can handle different exceptions separately:
try {
int arr[] = new int[3];
arr[5] = 10;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Index out of bounds!");
} catch (Exception e) {
System.out.println("Some error occurred");
}
Finally Block
The finally block always executes, whether an exception occurs or not.
try {
int data = 100 / 10;
} catch (Exception e) {
System.out.println("Error");
} finally {
System.out.println("Execution completed");
}
1️ ArithmeticException
Occurs when an illegal arithmetic operation is performed.
int x = 10 / 0;
2️NullPointerException
Occurs when trying to use a null reference.
java
String str = null;
System.out.println(str.length());
3️ ArrayIndexOutOfBoundsException
Occurs when accessing an invalid array index.
java
int arr[] = {1,2,3};
System.out.println(arr[5]);
Top comments (0)