Classic Tutorials for Java Beginners

Exceptions in Java

The full story of exceptions in the Java language and virtual machine

1 2 3 4 Page 4
Page 4 of 4

You can do anything inside a finally clause that you can do elsewhere, including executing break, continue, or return statements, or throwing exceptions. Such actions inside a finally clause, however, can have some surprising effects. For example, consider a finally clause that is entered because of an uncaught exception. If the finally clause executes a return, the method would complete normally via the return, not abruptly by throwing the exception. The exception would have in effect been handled by the finally clause instead of a catch clause.

As another example, consider a finally clause that is entered because a return true; statement was executed inside the try block. If the finally clause executes a return false; statement, the method will return false.

Conclusion

Java goes to great lengths to help you deal with error conditions. Java's exception mechanisms give you a structured way to perform a go-to from the place where an error occurs to the code that knows how to handle the error. These mechanisms also enable you to force client programmers (those who use your code by calling your methods) to deal with the possibility of an error condition encountered by your code. But Java's mechanisms do not force you to design your programs to take advantage of these capabilities. In the end, if you want your programs to handle error conditions in a structured, methodical way, you must use the exception mechanisms correctly.

For advice on how to put the exception mechanisms described in this article to use in your programs and designs, see this month's Design Techniques column, "Designing with exceptions."

Bill Venners has been writing software professionally for 12 years. Based in Silicon Valley, he provides software consulting and training services under the name Artima Software Company. Over the years he has developed software for the consumer electronics, education, semiconductor, and life insurance industries. He has programmed in many languages on many platforms: assembly language on various microprocessors, C on Unix, C++ on Windows, Java on the Web. He is author of the book: Inside the Java Virtual Machine, published by McGraw-Hill.

Learn more about this topic

1 2 3 4 Page 4
Page 4 of 4