Types of Exceptions
In Java, exceptions are categorized into two main types: checked exceptions and unchecked exceptions.
Checked Exceptions
Checked exceptions are exceptions that must be declared in a method's signature or handled within the method using a try-catch block. These exceptions are typically expected and can be reasonably handled by the calling code.
Some common checked exceptions in Java include:
FileNotFoundException
: Thrown when a file is not found.IOException
: Thrown when an I/O error occurs.SQLException
: Thrown when a database access error occurs.
Here's an example that demonstrates how to handle a checked exception:
1import java.io.FileInputStream;
2import java.io.FileNotFoundException;
3
4public class Main {
5 public static void main(String[] args) {
6 try {
7 FileInputStream file = new FileInputStream("example.txt");
8 // Process the file
9 } catch (FileNotFoundException e) {
10 System.out.println("File not found!");
11 }
12 }
13}
Unchecked Exceptions
Unchecked exceptions are exceptions that do not need to be declared in a method's signature or handled explicitly. These exceptions typically represent programming errors or unexpected conditions that cannot be recovered from.
Some common unchecked exceptions in Java include:
NullPointerException
: Thrown when a null reference is accessed.IndexOutOfBoundsException
: Thrown when an index is out of range.ArithmeticException
: Thrown when an arithmetic operation results in an illegal or undefined value.
Here's an example that demonstrates an unchecked exception:
1public class Main {
2 public static void main(String[] args) {
3 int[] numbers = {1, 2, 3};
4 int result = numbers[4]; // Throws ArrayIndexOutOfBoundsException
5 // Rest of the code
6 }
7}