sabaTEL.net

Java, MySQL, Avaya

Handling Exceptions

Exceptions is an elegant mechanism in Java for handling errors that produces organised error-handling code: exception handling. Which it allows us to keep the error treatment cleanly separated from the exception-generating code.

Exception means ‘exceptional condition’ and is an occurrence that alters the normal program flow. When an exceptional event occurs in Java, an exception is said to be ‘thrown’. The code responsible for doing something about the exception is called an ‘exception handler’ and it ‘catches’ the thrown exception.

Exception handling works by transferring the execution of a program to an appropriate exception handler when an exception occurs. An appropriate exception handler it can be a catch or a finally block. It’s mandatory that at least one of those blocks are present, we can have no more than one finally block.

It is important to pay attention to the exception hierarchy when we are building our exception handler going from the most specific to more general exceptions. The idea is, we are trying to catch the exception as accurate as possible from the beginning.

In the previous example if we swap the catch clause for FileNotFoundException with the handler for the IOException, the program will not compile!

Recommendation, try to avoid writing a single catchall exception, programming in this way defeats the design objective:

Advertisements

May 25, 2013 Posted by | Java | Leave a comment