Exception Handling
Exception Handling
Exception handling in Java is a mechanism that allows you to handle runtime errors, so the
normal flow of the application can be maintained. It helps in making your program more robust
and prevents it from crashing unexpectedly.
1. What is an Exception?
An exception is an event that occurs during the execution of a program and disrupts the normal
flow of instructions. It is an object that represents an error.
2. Types of Exceptions
catch
finally
Code that will execute no matter what (used for cleanup, like closing a file or DB connection).
throw
throws
🔹 Custom Exceptions
🔹 throws IOException
This part means that the method might throw an IOException, and it’s not handling it directly
inside the method. Instead, it passes the responsibility of handling the exception to whoever calls
the method.
This line creates a FileReader object, which tries to open and read the specified file.
If the file doesn’t exist, or there's an error accessing it, Java will throw an IOException.
That’s why the method must declare throws IOException.
4o
You said:
Absolutely! Here are a few more practical examples of exception handling in Java — each
showing different types of exceptions and how to handle them.
✅ 2. ArrayIndexOutOfBoundsException
public class ArrayExample {
public static void main(String[] args)
{
int[] numbers = {1, 2, 3};
try
{
System.out.println(numbers[5]); // invalid index
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("Error: Index out of bounds!");
}
}
}
✅ 3. NullPointerException
finally block
throw and custom exceptions
real-world cases (like login validation, API calls, etc.)