index (466)


Exceptions Chapter 18: Exceptions When a problem arises in a Java program, for instance when the program tries to write past the end of an array, the program creates and throws an exception. Like everything else in Java exceptions are objects, specifically subclasses of java.lang.Throwable. There are three kinds of Throwable object built-in to Java, Errors, Exceptions and RuntimeExceptions. Errors represent truly unexpected conditions that the Java compiler and virtual machine guarantee will never occur. Unfortunately Murphy's Law overrides the guarantees of the Java compiler and virtual machine, and Errors do occur. In general there's not much you can do about an error and trying to catch it will only make matters worse. Just let your program crash. Errors aren't very common. An Exception, on the other hand, violates some form of program logic but does not violate the structure of Java itself. By default an exception or error causes the thread from which it was thrown to gracefully halt execution while still cleaning up any memory it may have allocated. Depending on how carefully you typed the examples in previous days you may have already seen an "ArrayIndexOutOfBoundsException" or "NullPointerException." Although less than a perfect solution, this is still preferable to the core dump or General Protection Fault you'd see from a C program that wrote past the end of an array. However a program doesn't have to stop when an exception is thrown. By judicious use of try and catch statements a program can catch the exception and respond accordingly. In this chapter you'll learn What an exception is, what an error is and the difference between them How to catch exceptions What to do with exceptions once you've caught them. What a Runtime Exception Is How to throw exceptions of your own devising Example 18.1: Test The Randomness of a Random Number Generator Example 18.2: Throwing New Exceptions Examples from Other Chapters [ Cafe Au Lait | Books | Trade Shows | Links | FAQ | Tutorial | User Groups ] Copyright 1996 Elliotte Rusty Harold elharo@sunsite.unc.edu Last Modified July 23, 1996

Wyszukiwarka

Podobne podstrony:
index
index
index
index
index
index
index
index

więcej podobnych podstron