Should class IOException in Java have been an unchecked RuntimeException?

前端 未结 6 1022
夕颜
夕颜 2021-02-05 05:29

Do you agree that the designers of Java class java.io.IOException should have made it an unchecked run-time exception derived from java.lang.RuntimeException<

6条回答
  •  青春惊慌失措
    2021-02-05 06:21

    In a well-designed exception framework, a distinction should be made between exceptions which are to some extent "expected" and those which are not. Java attempts to use checked versus unchecked exceptions for this. By that standard, IOException should be a checked exception.

    A fundamental problem, though, is that oftentimes code will be written with a (perhaps reasonable) expectation that a certain exception will not occur, and nothing can usefully be done to handle it if it does. If a method is declared as throwing a particular checked exception, Java allows its caller to ignore the exception if it declares itself as throwing that exception, but there's no means by which a method or code block can specify that certain exceptions from called methods are not expected to occur. A common anti-pattern is:

    try
    {
      methodThatsDeclaredAsThrowingFooExceptionButWont()
    }
    catch FooException Ex
    {
      // Never going to happen
    }
    

    The apparent assumption is that since the method won't throw FooException and the only reason the catch is there is to make the compiler happy, there's no reason for the catch to do anything. Insidious, because if a FooException does get thrown, for whatever reason, it will go undetected.

    An alternative is for a method which calls methodThatsDeclaredAsThrowingFooExceptionButWont to declare itself as throws FooException or throws Exception, but that isn't really appropriate either. If a method which is not expected to throw a FooException does, the system state is apt to be different from what it would be expected when a FooException is thrown.

    For example, suppose one attempts to load a document, but the document-load routine needs to read some non-document-specific translation tables which are supposed to be stored at a fixed location; if that attempt fails, having the IOException percolate up to the caller would imply that there was a problem loading the document being loaded. If the load-document routine isn't prepared to sensibly handle the possibility that the load-translation-tables routine might fail, such failure shouldn't percolate up the same way as would an IOException that occurred while actually loading the document.

    The proper remedy would not be for IOException to be an unchecked exception, but rather for there to be a declarative means by which code could indicate that one or more kinds of checked exceptions should not be allowed to percolate out of a certain block from methods called thereby, but should instead be wrapped in some other exception type (e.g. RuntimeException).

提交回复
热议问题