Lesson 26Handling Exceptions

It is inevitable that your programs will sometimes have errors. These can be errors within your code such as dividing by zero, errors caused by bad data, or errors caused by numerous other reasons. Error conditions in Java are represented by exceptions. The Java mechanisms for handling exceptions are the try, catch, and finally constructs and the throws keyword.

One of the marks of a professional developer is that their programs handle exceptions and recover gracefully. This means that predictable error conditions are expected and do not crash the program because additional code is written to handle these runtime errors.

EXCEPTION HANDLING

There are two types of errors: runtime and compiletime. Compiletime errors must be fixed before you can compile and run your application. Runtime errors occur when your code is syntactically correct, but an unexpected issue occurs while running the application.

An example of a runtime exception is when your application attempts to access a file that isn't there or attempts to divide by zero. Opening a file and division are both valid code statements, so the application compiles fine. However, if a user enters a 0 denominator while the application ...

Get Job Ready Java 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.