Java practical tips: When a checked exception cannot be thrown

Source: Internet
Author: User

One problem with the checked exception is that it is sometimes not allowed to throw such exceptions. In particular, if you want to override the methods declared in the superclass or implement the methods declared in the interface, and that method does not declare any checked exception, then the new implementation cannot declare a checked exception.

Therefore, you must handle the exception in advance. In addition, you can convert the exception to a runtime exception or bypass it without handling it. But should this be done? Is there any hidden error?

Related Article recommendations: three common Java exceptions and solutions for how to use Java exceptions to throw

Problem

You only need to look at an example to clarify the problem. Suppose there is a List of File objects, which must be sorted alphabetically by their standard paths. The so-called standard path refers to the complete absolute path obtained after the alias, symbolic link, and/./And/./are parsed. The local method uses a comparator, as shown in Listing 1:

Listing 1. compare two files in the standard path: importjava. io. file; importjava. io. IOException; importjava. util. arrayList; importjava. util. collections; importjava. util. comparator; publicclassFileComparatorimplementsComparator <File> {publicintcompare (Filef1, Filef2) {returnf1.getCanonicalPath (). compareTo (f2.getCanonicalPath ();} publicstaticvoidmain (String [] args) {ArrayList <File> files = newArrayList <File> (); for (Stringarg: args) {file S. add (newFile (arg);} Collections. sort (files, newFileComparator (); for (Filef: files) {System. out. println (f) ;}}unfortunately, the Code cannot be compiled. The problem is that the getCanonicalPath () method throws an IOException because it needs to access the file system. When a checked exception is used, you can use either of the following methods:

1. Wrap the error code in a try block and capture the thrown exception.
2. Declaring the packaging method (compare () in this example) also throws an IOException.

Generally, the method you choose depends on whether the exception can be properly handled when an exception is thrown. If yes, use the try-catch Block. If not, the declared packaging method itself throws an exception. Unfortunately, these two skills are not used in this example. IOException cannot be handled reasonably in the compare () method. Technically speaking, it seems that-returns 0, 1, or-1, as shown in Listing 2:

List 2. when an exception is thrown, a default value publicintcompare (Filef1, Filef2) {try {returnf1.getCanonicalPath () is returned (). compareTo (f2.getCanonicalPath ();} catch (IOExceptionex) {return-1 ;}} however, this violates the compare () method Convention because it is not a stable result. For the same object, the first and second calls may produce different results. If this comparator is used for sorting, it means that the final list is not correctly sorted. So now try the 2nd option-declare compare () to throw an IOException:

Publicintcompare (Filef1, Filef2) throwsIOException {returnf1.getCanonicalPath (). compareTo (f2.getCanonicalPath ();} This cannot be compiled either. Because the checked exception is part of the method signature, the checked exception cannot be added when the method is overwritten, just as the return type cannot be changed. At last, there is a compromise: capture an exception in compare (), convert it to a runtime exception, and then throw a runtime exception, as shown in listing 3:

Listing 3. convert a checked exception to a runtime exception publicintcompare (Filef1, Filef2) {try {returnf1.getCanonicalPath (). compareTo (f2.getCanonicalPath ();} catch (IOExceptionex) {thrownewRuntimeException (ex) ;}} unfortunately, this method does not work even though it can be compiled, the reason is more subtle. The Comparator interface defines a contract (see references ). This contract does not allow this method to throw a runtime exception (preventing a bug in the calling code due to a violation of generic type security ). The method using this comparator reasonably relies on it to compare two files without throwing any exception. They are not ready to handle unexpected exceptions in compare.

It is precisely for this subtle reason that it is a bad idea to make runtime exceptions an external condition for the code to handle. This just avoids the problem and does not really solve the problem. The adverse consequences of not handling exceptions still exist, including data destruction and incorrect results.

In this way, you are in trouble. You cannot handle exceptions effectively within compare () or beyond compare. What else can be done to handle exceptions-System. exit ()? The only correct solution is to completely avoid this dilemma. Fortunately, there are at least two ways to do this.

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.