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:


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

Unreachable code

A typical question that we can expect at the exam is given a code that has no errors, try simulate the execution to find out what will be the score.

In those kind of questions, you don’t expect (at least I wasn’t expecting) the compiler to complain about a condition that can never be satisfied in order to execute certain code.

In this example, the fact that we are throwing an exception at the try block means that line 10 will never be executed. The Exception will be catch but we will never return to finish the rest of the try block.

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