Java provides a set of predefined exceptions, known as built-in exceptions, which are part of the Java Standard Library. These exceptions are subclasses of java.lang.Exception or java.lang.RuntimeException, and they help handle common errors that may occur during the execution of a program. Built-in exceptions can be categorized into checked and unchecked exceptions.
Types of Built-In Exceptions
- Checked Exceptions:
- Checked exceptions are exceptions that are checked at compile-time. The Java compiler ensures that these exceptions are either handled with a try-catch block or declared in the method signature using the throws keyword.
- Examples:
- IOException
- SQLException
- FileNotFoundException
- ClassNotFoundException
- Unchecked Exceptions:
- Unchecked exceptions are exceptions that are not checked at compile-time. These exceptions are derived from RuntimeException and its subclasses.
- Examples:
- ArithmeticException
- NullPointerException
- ArrayIndexOutOfBoundsException
- ClassCastException
- Errors:
- Errors are not exceptions and are used to indicate severe problems that a program usually cannot recover from (e.g., OutOfMemoryError, StackOverflowError).
Common Built-In Exceptions
1. ArithmeticException
- Description: Thrown when an illegal arithmetic operation is performed, such as dividing by zero.
- Example:
int a = 10;
int b = 0;
try {
int result = a / b; // This will throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println(“Cannot divide by zero.”);
}
2. NullPointerException
- Description: Thrown when a program attempts to access a method or field on a null object reference.
- Example:
String str = null;
try {
int length = str.length(); // This will throw NullPointerException
} catch (NullPointerException e) {
System.out.println(“Null pointer exception occurred.”);
}
3. ArrayIndexOutOfBoundsException
- Description: Thrown when an array is accessed with an illegal index (negative or greater than the array size).
- Example:
int[] arr = new int[5];
try {
int value = arr[10]; // This will throw ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(“Array index out of bounds.”);
}
4. ClassNotFoundException
- Description: Thrown when an application tries to load a class that cannot be found.
- Example:
try {
Class.forName(“com.example.MyClass”); // Throws ClassNotFoundException if the class is not found
} catch (ClassNotFoundException e) {
System.out.println(“Class not found.”);
}
5. IOException
- Description: Thrown when there is an input/output operation failure.
- Example:
try {
FileReader reader = new FileReader(“nonexistentFile.txt”); // Throws IOException
} catch (IOException e) {
System.out.println(“File not found or I/O error occurred.”);
}
6. FileNotFoundException
- Description: A subclass of IOException thrown when an attempt to open a file that does not exist is made.
- Example:
try {
FileInputStream file = new FileInputStream(“file.txt”);
} catch (FileNotFoundException e) {
System.out.println(“The file was not found.”);
}
7. SQLException
- Description: Thrown when there is an issue with database access.
- Example:
try {
Connection conn = DriverManager.getConnection(“jdbc:mysql://localhost:3306/db”, “user”, “password”);
} catch (SQLException e) {
System.out.println(“Database connection error.”);
}
8. ClassCastException
- Description: Thrown when an invalid cast is performed between incompatible types.
- Example:
Object obj = “Hello”;
try {
Integer num = (Integer) obj; // This will throw ClassCastException
} catch (ClassCastException e) {
System.out.println(“Invalid type casting.”);
}
Checked vs. Unchecked Exceptions
- Checked Exceptions:
- Must be either caught or declared in the throws clause of the method.
- Example: IOException, SQLException, FileNotFoundException
- Unchecked Exceptions:
- Do not need to be caught or declared in the throws clause.
- Example: ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException
Key Difference:
- Checked exceptions are intended to be handled by the programmer as they indicate recoverable conditions.
- Unchecked exceptions are generally due to programming errors that should be fixed in the code, not caught during runtime.
Handling Built-In Exceptions
Built-in exceptions can be handled using try-catch blocks to catch and process them gracefully.
Example:
public class ExceptionHandlingExample {
public static void main(String[] args) {
try {
int[] arr = new int[2];
int value = arr[3]; // This will throw ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(“An array index out of bounds exception occurred: ” + e.getMessage());
}
try {
int result = 10 / 0; // This will throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println(“Cannot divide by zero: ” + e.getMessage());
}
}
}
Output:
An array index out of bounds exception occurred: Index 3 out of bounds for length 2
Cannot divide by zero: / by zero
Best Practices for Handling Exceptions
- Handle Only What You Can Handle: Catch exceptions only when you can recover from them or log meaningful information.
- Use Specific Exceptions: Catch specific exceptions before more general ones to handle each type appropriately.
- Avoid Catching Exception or Throwable: Catching these can mask other issues and make debugging difficult.
- Use finally for Cleanup: Use a finally block to ensure that resources are released, even if an exception occurs.
- Throw Custom Exceptions When Needed: If the built-in exceptions do not fit the context of your program, create custom exceptions.
Conclusion
Built-in exceptions in Java provide a way to handle various errors that occur during program execution. Understanding when and how to use them, and knowing the difference between checked and unchecked exceptions, is essential for writing robust and maintainable Java applications. Properly handling these exceptions ensures your program can respond gracefully to unexpected situations.