Chapter 13

Error Handling

Fixing the compiler’s errors becomes trivial as you become more comfortable with the Java syntax. But you also should ensure that your programs process run-time errors that may happen regardless of your proficiency with the language itself.

Let’s say a Java program that reads customers’ data is deployed in production. What’s going to happen if this file gets corrupted? Will the program crash with a scary geeky error message, or will it stay alive, displaying a user-friendly message such as, “There seems to be a problem with the file customers. Please make sure that the file is not corrupted”? Error processing in the Java world is called exception handling, which is the subject of this lesson.

Stack Trace

When a Java application is running, the JVM performs a number of internal and application-specific method calls. If a run-time error occurs that’s not handled by the program, the program prints a stack trace, which reflects in the call stack the sequence of unfortunate events that caused this error. A stack trace helps software developers follow the workflow of the program that led to the error.

To illustrate what a stack trace may look like, consider the program shown in Listing 13-1, which deliberately divides by zero.

download.eps

Listing 13-1: Generating stack trace by dividing by zero

 1 class TestStackTrace{     2    TestStackTrace() 3    { 4        divideByZero(); ...

Get Java® Programming 24-Hour Trainer now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.