Lesson 10Error 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 handle runtime errors that may happen regardless of your proficiency with the language itself.

Let’s say you have a Java program that reads customers’ data from a file 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. An exception is a runtime error that may stop the execution of your program.

Stack Trace

When a Java application is running, the JVM performs a number of internal and application-specific method calls. If a runtime 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 10-1, which deliberately divides by zero.

Get Java Programming 24-Hour Trainer, 2nd Edition 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.