Search code examples
javaexceptionchecked-exceptions

Isn't an unchecked exception that is caught in a try block a checked exception in Java?


I was told that in Java, unchecked exceptions can be caught in a try block, but if it's caught, isn't it called a checked exception?


Solution

  • Unchecked exceptions are exceptions that don't need to be caught in a try-catch block. Unchecked exceptions are subclasses of the RuntimeException or Error classes.

    Checked exceptions are exceptions that need to be caught in a try-catch block.

    The definition of checked and unchecked exceptions can be found in Section 11.2: Compile-Time Checking of Exceptions of The Java Language Specification:

    The unchecked exceptions classes are the class RuntimeException and its subclasses, and the class Error and its subclasses. All other exception classes are checked exception classes.

    Just because an unchecked exception is caught in a catch block does not make it a checked exception -- it just means that the unchecked exception was caught, and was handled in the catch block.

    One could catch an unchecked exception, and then throw a new checked exception, so any methods calling that method where an unchecked exception could occur and force an method that calls it to handle some kind of exception.

    For example, a NumberFormatException which can be thrown when handling some unparsable String to the Integer.parseInt method is an unchecked exception, so it does not need to be caught. However, the method calling that method may want its caller to properly handle such a problem, so it may throw another exception which is checked (not a subclass of RuntimeException.):

    public int getIntegerFromInput(String s) throws BadInputException {
        int i = 0;
        try {
            i = Integer.parseInt(s);
        catch (NumberFormatException e) {
            throw new BadInputException();
        }
    
        return i;
    }
    

    In the above example, a NumberFormatException is caught in the try-catch block, and a new BadInputException (which is intended to be a checked exception) is thrown.

    Any caller to the getIntegerFromInput method will be forced to catch a BadInputException, and forced to deal with bad inputs. If the NumberFormatException were not to be caught and handled, any callers to this method would have to handle the exception correctly.

    (Also, it should be noted, eating an exception and doing something that is not really meaningful is not considered a good practice -- handle exceptions where meaningful exception handling can be performed.)

    From The Java Tutorials: