Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Ganesh_JavaSE7_Programming_1z0-804_study_guide.pdf
Скачиваний:
94
Добавлен:
02.02.2015
Размер:
5.88 Mб
Скачать

Chapter 11 Exceptions and Assertions

D:\> java ScanInt7

Type an integer in the console: ten

Error: Encountered an exception and could not read an integer from the console...

Exiting the program - restart and try the program again! Done reading the integer... closing the Scanner

Yes, the statement “Done reading the integer... closing the Scanner” is called whether an exception is thrown or not. Note that you can have a finally block directly after a try block without a catch block as well; this feature is used rarely, but is nevertheless a useful feature.

Points to Remember

Here are some interesting points related to throwing /handling exceptions and releasing resources in a finally block:

You can catch exceptions and wrap them into more generic exceptions and throw them higher up in the call stack. When you catch an exception and create a more general exception, you can retain reference to the original exception; this is called exception chaining.

catch(LowLevelException lle) {

    // wrap the low-level exception to a higher-level exception;

//also, chain the original exception to the newly thrown exception

    throw new HighLevelException(lle);

}

Chaining exceptions is useful for debugging purposes. When you get a general exception,

you can check if there is a chained lower-level exception and try to understand why that lowerlevel exception occurred.

The finally statement is always executed irrespective of whether the code in the try block throws an exception or not. Consider the following method. Will it return true or false to the caller? 

static boolean returnTest() {

        try {

                return true;

        }

        finally {

                return false;

        }

} 

This method will always return false because finally is always invoked. In fact, if you use the –Xlint option, you’ll get this compiler warning: “finally clause cannot complete normally.” (Note that you can have a try block followed by either catch block or finally block or both blocks.)

330

Chapter 11 Exceptions and Assertions

Precise Rethrow

Consider the following program:

class PreciseRethrow {

     public static void main(String []str) {

                try {

                        foo();

                }

                catch(NumberFormatException ife) {

                        System.out.println(ife);

                }

     }

        static private void foo() throws NumberFormatException {

                try {

                        int i = Integer.parseInt("ten");

                }

                catch(Exception e) {

                        throw e;

                }

     }

}

If you try this program in Java versions earlier to Java 1.7, you’ll get this error:

C:\> javac -source 1.6 PreciseRethrow.java

PreciseRethrow.java:16: error: unreported exception Exception; must be caught or declared to be thrown

throw e;

^

1 error 

In this program, the Integer.parseInt() method can throw a NumberFormatException. However, the catch block declares catching the general exception type Exception. Inside the catch block, the exception is rethrown. Now, the method foo()’s throws clause indicates it can throw the NumberFormatException, which is correct because it is the only exception that the Integer.parseInt() method can throw. However, since the static type of the rethrown exception is Exception, the compiler will complain that the throws clause of the foo() method should declare Exception.

Java 7 allows you to be more precise when you rethrow an exception. If you rethrow an exception from a catch block, you can throw a type that the try block can throw but no previous catch handles has handled it. Also, the rethrown exception type need not be same as the catch type parameter; it can be a subtype of the catch

parameter. Hence the class PreciseRethrow given above will compile without warnings or errors. (Of course the program will crash after throwing NumberFormatException because the string “ten” is not an integer!)

331

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]