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

Chapter 11

Exceptions and Assertions

 

Use throw and throws statements

 

Use the try statement with multi-catch, and fanally clauses

Exam Topics

Autoclose resources with a try-with-resources statement

 

Create custom exceptions

 

Test invariants by using assertions

In this chapter, you’ll learn about Java’s support for exception handling in detail. You’ll first learn the basic concepts behind exception handling and then you’ll learn how to throw, catch, and rethrow exceptions. You’ll also learn about the recently added language features such as try-with-resources and multi-catch statements. Following that, you’ll learn how to define your own exception classes (custom exceptions). Finally, we’ll discuss the related topic of assertions and teach you how to use them in your programs. Most of the programming examples in this chapter make use of I/O functions (Chapters 8 and 9) to illustrate the concepts of exception handling.

Introduction to Exception Handling

As programmers, we are optimistic—we just write code to solve the problem at hand and expect it to work without any problems. However, things do go wrong (more often than we’d like!), so we should always anticipate errors and exceptions, and write code to handle the exceptional conditions.

Java has built-in support for exceptions. The Java language supports exception handling in the form of the throw, throws, try, catch, and finally keywords. See Figure 11-1 to understand the basic syntax of these keywords.

317

Chapter 11 Exceptions and Assertions

The checked exception ACheckedException can be thrown from the body of the method foo( ).

The code inside try block can

public static void foo() throws ACheckedException {

try

{

throw exceptions.

 

// some code that can throw an exception ...

 

 

If the code in try block throws an exception

} catch

(Exception e){

 

// handle the exception

of type Exception or its derived classes, this

}

catch block code will handle it.

{

 

 

finally

 

The code in finally block will always be

}

// release resources acquired in the try block

 

 

executed (doesn’t matter if the try block

 

 

throw an exception or not).

 

 

{

 

if(someCondition)

This throw statements throws the custom

} else {

throw new ACheckedException();

checked exception (and since there is no

 

 

catch hander for this exception, it must be

 

throw new AnUnCheckedException();

declared in throws clause of the metnod).

}

 

 

}

 

 

 

 

 

This throw statement throws AnUncheckedException (since this is an unchecked exception it is not declared in the throws clause).

Figure 11-1.  The basic syntax of exception handling-related keywords

Throwing Exceptions

Listing 11-1 is a very simple programming example in which you want to echo the text typed as command-line arguments back to the user. Assume that the user must type some text as command-line arguments to echo, or else you need to inform the user about the “error condition.”

Listing 11-1.  Echo.java

// A simple program without exception handling code class Echo {

        public static void main(String []args) {

                if(args.length == 0) {

// no arguments passed – display an error to the user

                        System.out.println("Error: No input passed to echo command... ");

                        System.exit(-1);

                }

                else {

                        for(String str : args) {

// command-line arguments are separated and passed as an array

                                // print them by adding a space between the array elements

                                System.out.print(str + " ");

                        }

                }

        }

}

318

q

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