Site MapHelpFeedbackExceptions and Assertions
Exceptions and Assertions


When someone says his or her program is reliable, what do we expect from the program? The majority of people would probably reply correctness as the most important criterion in determining the reliability of a program. When a program is claimed to be reliable, we certainly expect the program will produce correct results for all valid input. It is hardly a reliable program if it produces correct results only for some input values. As we all know by now, writing a correct program is easier said than done. If we are not diligent and careful enough, we can easily introduce bugs in our programs. And often we fail to eradicate them. A mechanism called an assertion can be used to improve the likelihood of catching logical errors during the development. We will introduce assertions in this chapter and show how to use them effectively in our programs.

Program correctness guarantees correct results for all valid input. But what happens when the input is invalid? Another important criterion of program reliability is the robustness, which measures how well the program runs under various conditions. If a program crashes too easily when a wrong type of argument is passed to a method or an invalid input value is entered, we cannot say the program is very reliable. A mechanism called exception handling can be used to improve the program’s robustness. In this chapter, we will describe how to code this exception-handling mechanism in Java to improve the program’s robustness.

O b j e c t i v e s

After you have read and studied this chapter, you should be able to

Improve the reliability of code by incorporating exception-handling and assertion mechanisms.

Write methods that propagate exceptions.

Implement the try-catch blocks for catching and handling the thrown exceptions.

Write programmer-defined exception classes.

Distinguish between the checked and unchecked, or runtime, exceptions.

Use assertions in methods to increase the chance of detecting bugs during the development.







WuOnline Learning Center

Home > Chapter 8