One problem with the checked exception is that it is sometimes not allowed to throw such an exception. In particular, if you want to overwrite a method declared in a superclass, or implement a method declared in an interface, and that method does not declare any checked exception, then the new implementation cannot declare the checked exception. Therefore, exceptions must be handled in advance. Alternatively, you can convert an exception to a Run-time exception, or bypass it without handling it. But should this be the case, is there a hidden error?
Problem
Just look at one example and the problem is clear. Suppose you have a List of File objects that you want to sort by their standard paths in dictionary order. The so-called standard path refers to the parsing of aliases, symbolic links and/. /and the complete absolute path obtained after/./. The local method uses a comparer, as shown in Listing 1:
Listing 1. Compare two files by standard path
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class FileComparator implements Comparator<File> {
public int compare(File f1, File f2) {
return f1.getCanonicalPath().compareTo(f2.getCanonicalPath());
}
public static void main(String[] args) {
ArrayList<File> files = new ArrayList<File>();
for (String arg : args) {
files.add(new File(arg));
}
Collections.sort(files, new FileComparator());
for (File f : files) {
System.out.println(f);
}
}
}
Unfortunately, the code cannot be compiled. The problem is that the Getcanonicalpath () method throws a IOException because it requires access to the file system. Typically, when you use checked exceptions, you can use one of the following two methods:
Wraps the error code in a try block and catches the thrown exception.
Declaring the wrapper method (in this case compare ()) also throws a IOException.
Usually, the choice of method depends on whether the exception can be handled reasonably when the exception is thrown. If you can, then use the Try-catch block. If not, then declaring the wrapper method itself throws an exception. Unfortunately, neither of these techniques works for this example.
IOException cannot be handled reasonably in the Compare () method. Technically, it seems possible-that is, return 0, 1, or-1, as shown in Listing 2: