Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

Share this Page URL

Chapter 7. Error Handling - Pg. 155

Chapter 7 Error Handling Error handling is an important feature in any programming language. A good error handling mechanism makes it easier for programmers to write robust applications and prevent bugs from creeping in. Programmers of some languages have to use many if statements to detect all possible conditions that might lead to an error. This could make your code excessively complex. In a larger program, this practice could easily lead to spaghetti like code. Java has a very nice approach to error handling by using the try statement. With this strategy, part of the code that could potentially lead to an error is isolated in a block. Should an error occur, this error is caught and resolved locally. This chapter teaches you how. Catching Exceptions You can isolate code that may cause a runtime error using the try statement, which normally is accompanied by the catch and finally statements. Such isolation typically occurs in a method body. If an error is encountered, Java stops the processing of the try block and jump to the catch block. Here you can gracefully handle the error or notify the user by `throwing' a java.lang.Exception object. Another scenario is to re-throw the exception or a new Exception object back to the code that called the method. It is then the client's call to handle the error. If a thrown exception is not caught, the application will stop abruptly. This is the syntax of the try statement. try { [code that may throw an exception] } [catch (ExceptionType-1 e) { [code that is executed when ExceptionType-1 is thrown] }] [catch (ExceptionType-2 e) { 155