Java’s Built-in Exceptions

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.

  1. IOException:
  • Represents an error related to input or output operations.
  1. FileNotFoundException:
  • A subclass of IOException, specifically used to indicate that a file or directory could not be found.
  1. ParseException:
  • Indicates an error during the parsing of strings.
  1. SQLException:
  • Represents an error related to database access.
  1. 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.

  1. NullPointerException:
  • Thrown when attempting to access or modify an object with a null value.
  1. ArrayIndexOutOfBoundsException:
  • Indicates that an array has been accessed with an illegal index.
  1. ArithmeticException:
  • Thrown when an arithmetic operation exceeds the limits of its data type.
  1. IllegalArgumentException:
  • Thrown when a method receives an illegal argument.
  1. IllegalStateException:
  • Indicates that a method has been invoked at an illegal or inappropriate time.
  1. 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.

  1. OutOfMemoryError:
  • Thrown when the Java Virtual Machine (JVM) is unable to allocate an object because it is out of memory.
  1. 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:

  1. Catch Specific Exceptions:
  • Catch specific exceptions rather than using a generic catch (Exception e) block. This helps in handling different exceptions appropriately.
  1. 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.
  1. 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

ExceptionMeaning
ArithmeticExceptionArithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsExceptionArray index is out-of-bounds.
ArrayStoreExceptionAssignment to an array element of an incompatible type.
ClassCastExceptionInvalid cast
EnumConstantNotPresentExceptionAn attempt is made to use an undefined enumeration value
IllegalArgumentExceptionIllegal argument used to invoke a method
IllegalMonitorStateExceptionIllegal monitor operation, such as waiting on an unlocked
thread.
IllegalStateExceptionEnvironment or application is in incorrect state.
IllegalThreadStateExceptionRequested operation not compatible with current thread
state.
IndexOutOfBoundsExceptionSome type of index is out-of-bounds
NegativeArraySizeExceptionArray created with a negative size.
NullPointerExceptionInvalid use of a null reference.
NumberFormatExceptionInvalid conversion of a string to a numeric format
SecurityExceptionAttempt to violate security.
StringIndexOutOfBoundsAttempt to index outside the bounds of a string.
TypeNotPresentExceptionType not found.
UnsupportedOperationExceptionAn unsupported operation was encountered.
ClassNotFoundExceptionClass not found.
CloneNotSupportedExceptionAttempt to clone an object that does not implement the Cloneable
interface.
IllegalAccessExceptionAccess to a class is denied.
InstantiationExceptionAttempt to create an object of an abstract class or interface.
InterruptedExceptionOne thread has been interrupted by another thread
NoSuchFieldExceptionA requested field does not exist.
NoSuchMethodExceptionA requested method does not exist.

Leave a Comment