Joseph has posted 2 posts at DZone. View Full User Profile

Handling Exceptions in Java Using Eclipse

06.04.2010
| 13697 views |
  • submit to reddit
What exactly is an exception? Exceptions are irregular or unusual events that happen in a method the program is calling which usually occurs at runtime.  The method throws the Exception back to the caller to show that it is having a problem. If the programmer runs into this case, then they will need to extend an Exception from the Exception class that is already in the Java class library. In Eclipse, on the class declaration panel, the coder and request “constructors from superclass” and it will give the programmer constructors in a child Exception class that will accept error messages or the address of another Exception as a constructor parameter.  
 
When creating an Exception class, the programmer has to designate a kind of exception that must be caught or optionally caught. If you declare the Exception class to extend Exception as shown below, the compiler will insist that the method that is being thrown should also be in a caught in catch block.
 
public class CodeName extends Exception
{
…….
}

The compiler gives the programmer two choices when they call a method that throws an Exception that must be caught:
1. Add a try/catch in the code that is being call to catch the Exception
2. Pass the Exception back on to the caller

If the programmer chooses option two then they can do this by adding a "throws" clause to end of the method declaration line. The compiler will generate the code to pass the Exception back to the caller at run-time.  In the code below, the AnApplcation program is calling a Java Bean object's openFile() method, passing it the file name. The compiler will say to the openFile() method at compile time: "How do you want to handle the Exception?"

The AJavaBean should realize there is nothing they can do in the openFile() method to fix the problem so the programmer should throw the Exception back to AnApplication.  Eclipse can see the myProgram() in AnApplication is calling the openFile() method and when openFile() adds "throws FileNotFoundException" to its method declaration line, the compiler gives myProgram() method an error message asking the application method how it would like to handle the Exception.

public class AnApplication
{
public void myProgram()
{
bean.openFile(filename);
……
}
}

public class AJavaBean
{
public void openFile(String filename) throws FileNotFoundException
{
file.open(filename); //open() may throw FileNotFoundException
….
}
}

If the programmer choose the first method then they can see below that all the code to process, open, and read are put into a try block. Once a method is called that might throw and Exception, the call has to be from within a try block because there is a chance of failure.  If an Exception has been thrown by a method that is called in the try block shown below, the execution jumps out of the try block and into one of the catch blocks.  The code that is left below that point in the try block is skipped as you can tell from the structure below. Execution will continue out the bottom of the catch block which branches to the bottom of the catch group if the catch block doesn’t stop the method processing by doing a return.
 
Try/Catch example in Java:
public void myProgram()
{
try
{
bean.openFile(fileName); // throws FileNotFoundException
help.readFileContents(); // throws ReadException
do.processFileData(); // throws ProcessException
}
catch(FileNotFoundException ex)
{
System.out.println(ex); // calls toString() on ex
}
catch(ReadException ex)
{
System.out.println(ex); // calls toString() on ex
}
catch(ProcessException ex)
{
System.out.println(ex); // calls toString() on ex
}
}
}

What happen if it was really vital that we close the file we open at the top of the try block? If you close it at the bottom of the try block, an exception is thrown and the execution will never get to the bottom of the try block. To guarantee the file gets closed, you would have to repeat the close() action in every one of the catch blocks which becomes repetitive coding.  So you could remove all the close() and include a finally block at the bottom  like shown below. After the try block has been entered, the finally code will be executed. The finally code will also be executed also if a catch block is entered, even if the catch does a return.
 
public void myProgram()
{
try {
bean.openFile(fileName); // throws FileNotFoundException
help.readFileContents(); // throws ReadException
do.processFileData(); // throws ProcessException
}
catch(FileNotFoundException ex)
{
System.out.println(ex); // calls toString() on ex
}
catch(ReadException ex)
{
System.out.println(ea); // calls toString() on ex
}
catch(ProcessException ex)
{
System.out.println(ex); // calls toString() on ex
}
finally
{
bean.close(filename);
}
}
 
All the catch blocks print the Exception object’s toString() on the console as an error message. If you are not going to differentiate processing for different kinds of Exceptions, then you could use a “catch-all” block.  Since all exception objects are type Exception then they will be directed into this catch block as shown below.  Any unanticipated types of exception will be caught also.
 
public void myProgram()
{
try {
bean.openFile(fileName); // throws FileNotFoundException
helper.readFileContents(); // throws ReadException
do.processFileData(); // throws ProcessException
}
catch(Exception ex)
{
System.out.println(ex); // calls toString() on ex
}
finally
{
bean.close(filename);
}
}
Published at DZone with permission of its author, Joseph Randolph.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Alessandro Santini replied on Fri, 2010/06/04 - 5:38pm

Seriously, what is this? Why not speaking about the fail-fast principle or how to let exceptions flow gracefully upstream in the application stack or when to prefer a RuntimeException to an Exception when creating a new one?

Ricky Clarkson replied on Fri, 2010/06/04 - 11:43pm

Was this article intended to demonstrate what NOT to do? System.out.println(ex); loses the entire stack trace. ex.printStackTrace(); does not, or even better, throw new RuntimeException(ex); or a throws clause.

Veera Sundar replied on Sat, 2010/06/05 - 1:48am

Is this article for demonstrating the basics of Exception handling in Java? And, in the example catch blocks, the author eats all the exception messages which is a bad practice. :)

Oliver Weiler replied on Sat, 2010/06/05 - 3:26am

Besides other things, you should probably note that it is good practice to prefer the use of standard exceptions and only write new ones if you have to.

Chris Ainsley replied on Sat, 2010/06/05 - 5:45am

Have to agree with everyone here. This is a terrible way of doing things and I can only hope that any beginner would read these comments rather than accept this article at face value.

There are so many things wrong in the article. Swallowing the stack trace, catching granular exceptions with the exact same handler, using an object name that is a reserved word (do), but also performing an unguarded close in the finally block is a very bad idea too.

Stephane Vaucher replied on Sun, 2010/06/06 - 3:36pm

Actually, I think the author is a new developer and confuses many concepts. For one, I think he does not understand what Eclipse does (as he does not talk about eclipse in the article). He talks about the compiler as if it gives a programmer a choice. Also, I agree with most other responses. He probably does not talk about advanced concepts because he does not known them. I assume no one screens postings. I hope that if the article rating is low enough that the article is hidden from other novice programmers.

Gervais Blaise replied on Mon, 2010/06/07 - 2:11am

Actually, I think the author is a new developer and confuses many concepts.
I'm a 6 year old experienced Java developer. I dare posting comments since some only month and I dream writing articles on javalobby. Javalobby isn't a sandbox. It is a reference place for developers. If "you" are not absolutely confident with what you want to post, don't post it. A bad article is a time loose and a bad point for a part of your developper life.

Sam Lewis replied on Mon, 2010/06/07 - 7:12am in response to: Gervais Blaise

Even a 6 year old can do exception handling better than this.

Jethro Borsje replied on Wed, 2010/06/09 - 2:13am

Is there no quality control on JavaLobby? I consider this website a great resources, but these kind of articles are just wasting my time.

Liezel Jane Jandayan replied on Thu, 2011/08/11 - 5:45am

No matter how you use Eclipse, most likely you will need to learn about the workbench.

 Senior Healthcare Consultants

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.