Exceptions: When Things Go Wrong

It is not a matter of IF but WHEN things will go wrong in a computer program. Sometimes there are bugs, errors of one form or another. There also also unforeseen use cases. You can never assume a computer program is perfect. Exception-Handling helps us to catch erroneous events and devise means of correcting them. We discuss this topic here since exception-handling can take more code than should be put into the main line of execution. In such cases, a method in an exception-handling class should be called. Exception handling mechanisms allow a program to continue executing, instead of terminating it abruptly, even if an error occurs in the program.

10.5 Error Handling and Robust Program Design

An important element of program design is to develop appropriate ways of handling erroneous and exceptional conditions. As we have seen, the JVM will catch any unchecked exceptions that are not caught by the program itself. For your own (practice) programs, the best design may simply be to use Java’s default exception handling. The program will terminate when an exception is thrown, and then you can debug the error and recompile the program.

On the other hand, this strategy would be inappropriate for commercial software, which cannot be fixed by its users. A well-designed commercial program should contain exception handlers for those truly exceptional conditions that may arise.

In general there are three ways to handle an exceptional condition that isn’t already handled by Java (Table 10.3). If the exceptional condition cannot be fixed, the program should be terminated, with an appropriate error message. Second, if the exceptional condition can be fixed without invalidating the program, then it should be remedied and the program’s normal execution should be resumed. Third, if the exception cannot be fixed, but the program cannot be terminated, the exceptional condition should be reported or logged in some way, and the program should be resumed.

Annotation 2020-03-29 172546

Annotation 2020-03-29 172618