Java Exceptions  «Prev 

Java Checked and Unchecked Exceptions

In Java, exceptions are divided into two categories: Checked Exceptions and Unchecked Exceptions. Here's a detailed comparison:
Checked Exceptions
  • Definition:Checked exceptions are exceptions that are checked at compile-time. This means if your method might throw a checked exception, you must either handle it using a try-catch block or declare it in the method's throws clause.
  • Examples:
    • IOException
    • SQLException
    • ParseException
  • Purpose: These exceptions represent problems that are recoverable but occur outside the immediate control of the program, like network issues or file system errors. They force the developer to acknowledge and handle these potential issues.
  • Handling Requirement: Must be caught or declared to be thrown:
    public void readFile() throws IOException {
     // Code that might throw IOException
    }
    

    Or handled:
    public void readFile() {
     try {
      // Code that might throw IOException
     } catch (IOException e) {
      // Handle the exception
     }
    }
    
  • Inheritance: They are subclasses of Exception but not of RuntimeException.


Unchecked Exceptions

  • Definition: Unchecked exceptions are exceptions that do not need to be explicitly handled or declared in the method signature. They are also known as runtime exceptions.
  • Examples:
  • Purpose:These exceptions represent programming errors or unforeseen conditions that are not expected to occur under normal circumstances. They often indicate bugs in the code.
  • Handling: While it's not mandatory to handle or declare these exceptions, it's often good practice to handle them if you can recover from the error or provide meaningful feedback:
    public void processArray(int[] arr) {
     try {
      // Code that might throw ArrayIndexOutOfBoundsException
     }catch (ArrayIndexOutOfBoundsException e) {
       System.out.println("Array index out of bounds!");
     }
    }
    
  • Inheritance:They are subclasses of RuntimeException, which itself is a subclass of Exception.

Key Differences:
  1. Compile-Time vs. Runtime: Checked exceptions are enforced at compile-time, while unchecked exceptions are not.
  2. Handling Requirement: Checked exceptions must be caught or declared, whereas unchecked exceptions do not have this requirement.
  3. Error Types: Checked exceptions often relate to external resources or system-level issues. Unchecked exceptions usually indicate errors in the logical structure of the program.
  4. Usage Context: Checked exceptions are used for conditions that the client code might reasonably be able to recover from or should be aware of. Unchecked exceptions are for conditions that represent a failure in the assumptions of the code.
  5. Philosophical Difference: Checked exceptions encourage explicit error handling, making it clear where errors might occur. Unchecked exceptions allow for a more flexible, "fail-fast" approach where the program crashes if an unexpected state is reached, which can be useful for debugging.

Best Practices:
  • Use Checked Exceptions for situations where the caller should know about the possibility of failure and can take action (e.g., retry, inform user).
  • Use Unchecked Exceptions for programmer errors or unexpected conditions that indicate a bug in the code.

Understanding these differences helps in designing robust and maintainable Java applications, where exceptions are used appropriately to handle errors and unexpected conditions.


Checked and Unchecked Exceptions

Question: What is the guideline for deciding between a checked and unchecked exception?
Answer: If a client can reasonably be expected to recover from an exception, make it a checked exception.

Exception Classifications

If a client cannot do anything to recover from the exception, make it an unchecked exception.
These categories are related to each other, and subclasses of the class java.lang.Exception are categorized as checked exceptions if they are not subclasses of the class java.lang.RuntimeException.
Subclasses of the class java.lang.RuntimeException are categorized as runtime exceptions. Subclasses of the class java.lang.Error are categorized as errors. Figure 2.8 illustrates the class hierarchy of these exception categories.

Checked Uncheked Exception
Figure 2.8: Object, Throwable, Error, Exception, RuntimeException


Checked Exceptions

  1. ClassNotFoundException: Class not found.
  2. CloneNotSupportedException: Attempt to clone an object that does not implement the Cloneable interface.
  3. IllegalAccessException: Access to a class is denied. IllegalAccessException signals that a particular method could not be found.
  4. InstantiationException: Attempt to create an object of an abstract class or interface.
  5. InterruptedException: One thread has been interrupted by another thread.
  6. NoSuchFieldException: A requested field does not exist.
  7. NoSuchMethodException: A requested method does not exist.
  8. ReflectiveOperationException - Superclass of reflection -related exceptions(Added by JDK 7.)

Modern Java

Runtime - Unchecked Exceptions

  1. ArithmeticException: Arithmetic error, such as divide-by-zero.
  2. ArrayIndexOutOfBoundsException: Array index is out-of-bounds.
  3. ArrayStoreException: Assignment to an array element of an incompatible type.
  4. ClassCastException: Invalid cast.
  5. EnumConstantNotPresentException: An attempt is made to use an undefined enumeration value
  6. IllegalArgumentException: Illegal argument used to invoke a method.
  7. IllegalMonitorStateException: Illegal monitor operation, such as waiting on an unlocked thread.
  8. IllegalStateException: Environment or application is in incorrect state.
  9. IllegalThreadStateException: Requested operation not compatible with current thread state.
  10. IndexOutOfBoundsException: Some type of index is out-of-bounds.
  11. NegativeArraySizeException: Array created with a negative size.
  12. NullPointerException: Invalid use of a null reference.
  13. NumberFormatException: Invalid conversion of a string to a numeric format.
  14. SecurityException: Attempt to violate security.
  15. StringIndexOutOfBounds: Attempt to index outside the bounds of a string.
  16. TypeNotPresentException: Type not found. (Added by J2SE 5.)
  17. UnsupportedOperationException: An unsupported operation was encountered.

SEMrush Software