In the end, you actually acknowledge and start to handle possible I/O errors, instead of escaping from them. You can even make more advanced error fixes. For example, IOComparator may not be overwhelmed by an I/O error-because many I/O problems are temporary-you can retry several times, as shown in listing 7:
Listing 7. If you fail at the beginning, try again several times (but do not try too many times)
Importjava. io. File;
Importjava. io. IOException;
PublicclassCanonicalPathComparatorimplementsIOComparator <File>
{
@ Override publicintcompare (Filef1, Filef2) throwsIOException
{
For (inti = 0; I <3; I ++)
{
Try
{
Returnf1.getCanonicalPath (). compareTo (f2.getCanonicalPath ());
}
Catch (IOExceptionex)
{
Continue;
}
}
// Lastchance returnf1.getCanonicalPath (). compareTo (f2.getCanonicalPath ());
}
}
This technique cannot solve the General Comparator problem, because you must retry countless times to avoid throwing exceptions, and many I/O problems are not temporary.
Is the checked exception a bad idea?
If java. io. IOException is a runtime exception rather than a checked exception, does the problem change? The answer is no. If IOException extends RuntimeException instead of java. lang. exception, so it is easier to compile code with bugs and incorrect code. This Code ignores the real possible I/O errors, and unexpectedly fails during running.
However, it is not easy to write correct, prepared, and able to handle I/O errors. Yes, this method is more complex than not having to prepare for unexpected I/O errors. However, removing the checked exception from the Java language does not help us achieve that ideal. I/O errors and other environmental problems are the norm, and active preparation is much better than turning a blind eye.
In short, the checked exception is not unreasonable as part of the method signature. When you find that you want to throw a checked exception from a method, which is not allowed-and thus suppress exceptions that shouldn't have been suppressed-then you can look back and reorganize it, consider why the method needs to be overwritten at the beginning. Probably, you should have taken a completely different approach.