๐ Introduction
Even the best code can go wrong. A file might not be found, a number might be divided by zero, or user input could be invalid.
Java handles such unexpected events using Exception Handling โ a powerful feature to manage runtime errors and avoid crashes.
โ What is an Exception?
An exception is an event that disrupts the normal flow of the program. Java provides a way to catch and handle these gracefully.
๐น Types of Exceptions
Type | Description | Example |
---|---|---|
Checked | Checked at compile time | IOException , SQLException |
Unchecked | Occur during runtime | NullPointerException , ArithmeticException |
๐งฏ try-catch Block โ Handle It Gracefully
โ Syntax:
try {
// code that might throw an exception
} catch (ExceptionType name) {
// handle the exception
}
๐ Example: Divide by Zero
public class Main {
public static void main(String[] args) {
try {
int result = 10 / 0; // risky
} catch (ArithmeticException e) {
System.out.println("Can't divide by zero!");
}
}
}
๐ finally Block โ Always Executes
Used for cleanup actions like closing files or database connections.
try {
// code
} catch (Exception e) {
// handling
} finally {
System.out.println("This always runs!");
}
๐ throw and throws โ Custom and Propagated Exceptions
๐น throw
โ Throw an Exception Manually
public class AgeChecker {
static void checkAge(int age) {
if (age < 18) {
throw new IllegalArgumentException("Underage not allowed!");
}
}
}
๐น throws
โ Declare That a Method May Throw
public void readFile(String path) throws IOException {
FileReader file = new FileReader(path);
}
๐จ Multiple catch Blocks
You can handle different exceptions separately:
try {
String s = null;
System.out.println(s.length());
} catch (NullPointerException e) {
System.out.println("Null reference!");
} catch (Exception e) {
System.out.println("Something went wrong!");
}
๐งช Challenge: Handle Array Index Exception
public class ArrayExample {
public static void main(String[] args) {
int[] nums = {1, 2, 3};
try {
System.out.println(nums[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Index out of bounds!");
}
}
}
๐ง Best Practices
- Catch specific exceptions first.
- Use finally to release resources.
- Avoid catching
Exception
blindly unless absolutely necessary.
โ What You Learned
- What exceptions are and why they matter
try
,catch
,finally
,throw
, andthrows
- Handling both built-in and custom exceptions