In Java, exceptions are events that occur during the execution of a program and disrupt its normal flow. They represent situations that the programmer might want to handle, such as errors or unexpected conditions. Java provides a robust exception-handling mechanism to deal with these situations.
Java classifies exceptions into two main types:
-
Checked Exceptions:
- These are exceptions that the compiler requires you to catch or declare. They extend the
Exceptionclass. - Examples:
IOException,ClassNotFoundException.
- These are exceptions that the compiler requires you to catch or declare. They extend the
-
Unchecked Exceptions (Runtime Exceptions):
- These are exceptions that occur at runtime and do not need to be explicitly caught or declared.
- They extend the
RuntimeExceptionclass. - Examples:
NullPointerException,ArrayIndexOutOfBoundsException.
try {
// Code that may throw an exception
// ...
} catch (ExceptionType1 e1) {
// Handle ExceptionType1
} catch (ExceptionType2 e2) {
// Handle ExceptionType2
} finally {
// Code that will be executed regardless of whether an exception occurs or not
}public void myMethod() throws MyException {
// Code that may throw MyException
// ...
}-
Catch Specific Exceptions:
- Catch specific exceptions rather than using a generic
catch (Exception e). This allows for more targeted handling.
- Catch specific exceptions rather than using a generic
-
Handle Exceptions Appropriately:
- Choose the appropriate handling strategy for each exception type (logging, rethrowing, or gracefully handling).
-
Use Finally Sparingly:
- Use the
finallyblock for cleanup code that should be executed regardless of whether an exception occurs or not.
- Use the
-
Avoid Empty Catch Blocks:
- Avoid empty
catchblocks as they can hide issues and make debugging challenging.
- Avoid empty
-
Log Exceptions:
- Consider logging exceptions using a logging framework to aid in debugging and troubleshooting.
-
IOException:
- Represents an error that occurs during input-output operations.
import java.io.FileReader; import java.io.IOException; public class CheckedExample { public static void main(String[] args) { try { FileReader fileReader = new FileReader("example.txt"); // Code that reads from the file fileReader.close(); } catch (IOException e) { e.printStackTrace(); } } }
-
ClassNotFoundException:
- Indicates that the specified class could not be found during runtime.
public class CheckedExample2 {
public static void main(String[] args) {
try {
Class.forName("com.example.NonExistentClass");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}-
NullPointerException:
- Occurs when trying to access or modify an object reference that is `null``.
public class UncheckedExample {
public static void main(String[] args) {
String str = null;
try {
int length = str.length();
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}-
ArrayIndexOutOfBoundsException:
- Thrown when attempting to access an array element at an invalid index.
public class UncheckedExample2 {
public static void main(String[] args) {
int[] numbers = {1, 2, 3};
try {
int value = numbers[5];
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}
}
}-
ArithmeticException:
- Occurs when an arithmetic operation results in an overflow, underflow, or division by zero.
public class UncheckedExample3 {
public static void main(String[] args) {
int result;
try {
result = 10 / 0;
} catch (ArithmeticException e) {
e.printStackTrace();
}
}
}-
IOException:
- Occurs during input-output operations, such as file handling.
-
ClassNotFoundException:
- Thrown when attempting to load a class by its string name, but the class definition is not found.
-
SQLException:
- Raised for database access issues, indicating an error with SQL.
-
FileNotFoundException:
- Raised when trying to access a file that cannot be found.
-
ParseException:
- Occurs when parsing operations fail, such as parsing a date or number from a string.
-
NullPointerException:
- Thrown when trying to access or modify an object reference that is
null.
- Thrown when trying to access or modify an object reference that is
-
ArrayIndexOutOfBoundsException:
- Raised when attempting to access an array element at an invalid index.
-
ArithmeticException:
- Occurs when an arithmetic operation results in an overflow, underflow, or division by zero.
-
IllegalArgumentException:
- Thrown when a method receives an argument of an inappropriate type.
-
IllegalStateException:
- Raised when the state of an object is incompatible with the requested operation.
-
ClassCastException:
- Occurs when an attempt is made to cast an object to a subclass type, and the object is not an instance of that type.
-
NumberFormatException:
- Thrown when attempting to convert a string to a numeric format, but the string does not have the appropriate format.
-
NullPointerException:
- Raised when trying to access or modify an object reference that is
null.
- Raised when trying to access or modify an object reference that is
-
IndexOutOfBoundsException:
- General superclass for all exceptions related to accessing an index that is out of bounds.
-
ConcurrentModificationException:
- Thrown when a collection is modified while iterating over it.