What Is an Exception?
An exception is an unwanted event that interrupts the normal flow of the program.
Examples:
- Division by zero
- Accessing an invalid array index
- File not found
- Null pointer access Java uses objects to represent exceptions.
**⭐ Types of Exceptions
- Checked Exceptions**
- Known at compile time
- Must be handled using try-catch or declared with throws
*Examples:
*
- IOException
- SQLException
- FileNotFoundException
- Unchecked Exceptions
Known at runtime
Occur due to logical errors in the code
Examples:
- ArithmeticException
- NullPointerException
- ArrayIndexOutOfBoundsException
- Errors
Serious issues beyond the control of the program
Example:
- OutOfMemoryError
- StackOverflowError
⭐ Exception Handling Keywords
Keyword Meaning
- try -Wraps code that may throw an exception
- catch -Handles the exception
- finally -Always runs (even if exception occurs)
- throw -Throw an exception manually
- throws- Declare an exception in method signature
⭐ Basic Example
public class Example {
public static void main(String[] args) {
try {
int a = 10 / 0; // risky code
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
} finally {
System.out.println("This always executes.");
}
}
}
Output:
Cannot divide by zero!
This always executes.
⭐ Multiple Catch Blocks
try {
int arr[] = new int[5];
arr[10] = 50;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Invalid array index!");
} catch (Exception e) {
System.out.println("Other exception occurred.");
}
⭐ throws Keyword Example
void readFile() throws IOException {
FileReader fr = new FileReader("data.txt");
}
⭐ throw Keyword Example
if(age < 18){
throw new ArithmeticException("Not eligible to vote");
}
⭐ Why Use Exception Handling?
- Prevents program crashes
- Improves reliability
- Separates error-handling code from normal code
- Helps recover from unexpected situations
Top comments (0)