What is Java Exceptions?
In Java, an exception is an unwanted or unexpected event that disrupts the normal flow of a program. Exceptions occur during runtime and can arise due to logical errors, invalid inputs, or unforeseen conditions such as dividing by zero, accessing an invalid index in an array or trying to open a non-existent file.
What is an Exception in Java?
An exception is an object that represents an error or unexpected event. When an exception occurs, Java generates an object called the exception object, which contains information about the error, such as its type and location.
The process of handling exceptions ensures that the program continues to execute without crashing.
Key Terms in Exception Handling
- Exception: An abnormal condition that disrupts program execution.
- Try Block: A block of code where exceptions might occur.
- Catch Block: A block of code that handles the exception.
- Finally Block: A block that executes after the try and catch, regardless of whether an exception was handled.
- Throw: Used to explicitly throw an exception.
- Throws: Declares exceptions that a method can throw.
Types of Exceptions in Java
Java exceptions are broadly categorized into two types:
1. Checked Exceptions
- Checked at compile time.
- Must be handled using try-catch or declared using throws.
- Examples:
- IOException
- SQLException
2. Unchecked Exceptions
- Checked at runtime.
- Caused by programming mistakes.
- Examples:
- ArithmeticException
- NullPointerException
- ArrayIndexOutOfBoundsException
Java Exception Class Hierarchy
The exception hierarchy starts with the Throwable class, which has two main subclasses:
- Error: Represents serious issues that the program should not handle (e.g., OutOfMemoryError).
- Exception: Represents issues that the program can handle.
Hierarchy Diagram:
Throwable
├── Error
└── Exception
├── RuntimeException (Unchecked Exceptions)
└── Other Exceptions (Checked Exceptions)
How to Handle Exceptions in Java
1. Try-Catch Block
The try block contains code that may generate an exception. The catch block handles that exception.
Syntax:
try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
}
Example:
public class ExceptionExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // This will throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
}
}
}
Output:
Cannot divide by zero!
2. Finally Block
The finally block executes after try-catch, whether an exception occurs or not.
Example:
public class FinallyExample {
public static void main(String[] args) {
try {
int[] numbers = {1, 2, 3};
System.out.println(numbers[5]); // This will throw ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Invalid array index!");
} finally {
System.out.println("Execution completed.");
}
}
}
Output:
Invalid array index!
Execution completed.
3. Throw and Throws
- Throw: Used to explicitly throw an exception in a program.
- Throws: Declares exceptions that a method might throw.
Example with throw
:
public class ThrowExample {
public static void main(String[] args) {
checkAge(15); // Passing invalid age
}
public static void checkAge(int age) {
if (age < 18) {
throw new IllegalArgumentException("Age must be 18 or older.");
}
System.out.println("Access granted.");
}
}
Output:
Exception in thread "main" java.lang.IllegalArgumentException: Age must be 18 or older.
Example with throws
:
import java.io.*;
public class ThrowsExample {
public static void main(String[] args) throws IOException {
readFile("nonexistent.txt");
}
public static void readFile(String fileName) throws IOException {
FileReader file = new FileReader(fileName);
}
}
Common Java Exception Classes
Exception Class | Description |
---|---|
ArithmeticException | Thrown when an illegal arithmetic operation occurs. |
NullPointerException | Thrown when an object reference is null. |
IOException | Thrown during input/output operations failure. |
FileNotFoundException | Thrown when a file is not found. |
ArrayIndexOutOfBoundsException | Thrown when accessing an invalid array index. |
Custom Exceptions
Java allows you to define your own exception classes by extending the Exception class.
Example:
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
public class CustomExceptionExample {
public static void main(String[] args) {
try {
validateInput(0);
} catch (CustomException e) {
System.out.println(e.getMessage());
}
}
public static void validateInput(int number) throws CustomException {
if (number <= 0) {
throw new CustomException("Input must be greater than zero.");
}
}
}
Output:
Input must be greater than zero.