Java provides a comprehensive set of built-in exceptions, each designed to represent a specific type of error or exceptional condition that may occur during the execution of a program. These exceptions are organized into a hierarchy based on the Throwable
class. There are two main types of exceptions: checked exceptions and unchecked exceptions.
Checked Exceptions:
Checked exceptions are exceptions that must be either caught or declared in the method signature using the throws
clause. They extend the Exception
class.
- IOException:
- Represents an error related to input or output operations.
- FileNotFoundException:
- A subclass of
IOException
, specifically used to indicate that a file or directory could not be found.
- ParseException:
- Indicates an error during the parsing of strings.
- SQLException:
- Represents an error related to database access.
- ClassNotFoundException:
- Thrown when an application tries to load a class but the specified class cannot be found.
Unchecked Exceptions (RuntimeExceptions):
Unchecked exceptions, also known as runtime exceptions, do not need to be explicitly caught or declared. They extend the RuntimeException
class.
- NullPointerException:
- Thrown when attempting to access or modify an object with a
null
value.
- ArrayIndexOutOfBoundsException:
- Indicates that an array has been accessed with an illegal index.
- ArithmeticException:
- Thrown when an arithmetic operation exceeds the limits of its data type.
- IllegalArgumentException:
- Thrown when a method receives an illegal argument.
- IllegalStateException:
- Indicates that a method has been invoked at an illegal or inappropriate time.
- NumberFormatException:
- Thrown when trying to convert a string to a numeric type, but the string is not a valid number.
Errors:
Errors are typically caused by the environment or system, and they usually cannot be anticipated or recovered from by the application.
- OutOfMemoryError:
- Thrown when the Java Virtual Machine (JVM) is unable to allocate an object because it is out of memory.
- StackOverflowError:
- Occurs when the stack of a thread exceeds its specified size.
Custom Exceptions:
Developers can also create custom exceptions by extending either the Exception
class (for checked exceptions) or the RuntimeException
class (for unchecked exceptions). Custom exceptions allow developers to represent application-specific errors.
public class CustomException extends RuntimeException {
public CustomException(String message) {
super(message);
}
}
Best Practices for Exception Handling:
- Catch Specific Exceptions:
- Catch specific exceptions rather than using a generic
catch (Exception e)
block. This helps in handling different exceptions appropriately.
- Handle Exceptions at the Right Level:
- Handle exceptions at a level where meaningful recovery or logging can take place. Avoid catching exceptions too early if they cannot be handled effectively.
- Use try-with-resources:
- When working with resources that implement
AutoCloseable
(e.g.,FileInputStream
,Scanner
), use try-with-resources to ensure proper resource management.
try (Scanner scanner = new Scanner(new File("example.txt"))) {
// Code that uses the scanner
} catch (FileNotFoundException e) {
// Handle file not found exception
}
Understanding and appropriately handling exceptions is crucial for writing robust and reliable Java programs. Effective exception handling contributes to improved error reporting, maintenance, and user experience.
Inside the standard package java.lang, Java defines several exception classes The most general of these exceptions are subclasses of the standard type RuntimeException In the language of Java, these are called unchecked exceptions because the compiler does not check to see if a method handles or throws these exceptions
java exception table list
Exception | Meaning |
---|---|
ArithmeticException | Arithmetic error, such as divide-by-zero. |
ArrayIndexOutOfBoundsException | Array index is out-of-bounds. |
ArrayStoreException | Assignment to an array element of an incompatible type. |
ClassCastException | Invalid cast |
EnumConstantNotPresentException | An attempt is made to use an undefined enumeration value |
IllegalArgumentException | Illegal argument used to invoke a method |
IllegalMonitorStateException | Illegal monitor operation, such as waiting on an unlocked thread. |
IllegalStateException | Environment or application is in incorrect state. |
IllegalThreadStateException | Requested operation not compatible with current thread state. |
IndexOutOfBoundsException | Some type of index is out-of-bounds |
NegativeArraySizeException | Array created with a negative size. |
NullPointerException | Invalid use of a null reference. |
NumberFormatException | Invalid conversion of a string to a numeric format |
SecurityException | Attempt to violate security. |
StringIndexOutOfBounds | Attempt to index outside the bounds of a string. |
TypeNotPresentException | Type not found. |
UnsupportedOperationException | An unsupported operation was encountered. |
ClassNotFoundException | Class not found. |
CloneNotSupportedException | Attempt to clone an object that does not implement the Cloneable interface. |
IllegalAccessException | Access to a class is denied. |
InstantiationException | Attempt to create an object of an abstract class or interface. |
InterruptedException | One thread has been interrupted by another thread |
NoSuchFieldException | A requested field does not exist. |
NoSuchMethodException | A requested method does not exist. |