advertisement
javaboutique
Search Tips
Articles  |   Tutorials  |   Reviews  |   Tools  |   by Category  |   by Date  |   by Name  |   Submit  |   Source  |   Forums  |  
javaboutique
Browse DevX


Partners & Affiliates











advertisement


Tutorials : Using your own exception classes in Java :
Contents
Using your own exception classes in Java
Linking the Exception classes
New formatting routines in MyException

Using your own exception classes in Java

by Keld H. Hansen

Every application fails once in while. Even the ones built with Java, using design patterns, best practices, and a lot of good intentions. So we better prepare our applications for these situations, right? The first thing an application should do if it fails is to tell as much as possible about the error situation. For example: where exactly in the application did the error occur, what was the Java-method calling sequence, what data was being processed, and so on.

In this article I'll present a simple, systematic approach which will help Java developers implement some solid error handling in their code. The building blocks are Java's Exception-classes.

The basic stuff about Java Exceptions

I'll not go through all the details of Java's exceptions, there are lot of good books and articles about this. But a short intro might be nice as a starter.

Java uses exceptions to report severe errors. If a Java statement fails to execute, the Java VM will create a new instance of an Exception class--or subclass thereof--and then "throw" it. A program can "catch" such an exception, inspect it using its methods, and then try to do something sensible to handle the error.

By "severe errors" I refer to situations in a program which the programmer does not consider "normal". This could be a database connection that suddenly drops, an attempt to divide by zero, or anything else that is vital to the proper functioning of a program. What is NOT a severe error is for example when you get end-of-file reading a sequential file. Even if it does not occur frequently it's expected that it will occur, and you should therefore add code in your program to handle this situation.

It's a tradition in Java literature to illustrate the use of exceptions by a "division by zero" case, so why change this approach:

public float myDivide(int a, int b) {
  float r;
  try {
    r = a / b;
  }
  catch (ArithmeticException e) {
    System.out.println(e.getMessage());
    r = Float.POSITIVE_INFINITY;
  }
  return r;
}

In this code a divison by zero is caught, and the result is set to Java's value for "infinity". The example is merely to illustrate the technique. It would be simpler--and more correct--to test if "b" had the value zero before making the division.

An "ArithmeticException" is a subclass of "RuntimeException", which again is a subclass of class "Exception". All exceptions of class "Exception" or subclasses thereof--except "RuntimeException"s--must be caught. "FileNotFoundException" is not a "RuntimeException", so if you try to read a file with a statement like this

FileInputStream f = new FileInputStream("mydata.txt");

then the Java compiler would ask you to either "try-catch" "FileNotFoundException" or declare it in the throws clause of the method, like this:

public float someMethod() throws FileNotFoundException {...

Using the latter setup the caller of "someMethod" would again need to either catch this exception or to declare it in its own throws clause. If no-one catches an exception it'll end up in the "container" that runs the Java classes. This could be the Java VM, a servlet engine, or something else. The net result would be that the program stops and some error messages are written out, probably a Java-method stack trace containing the error information from the exception class which was thrown. This is indeed useful to the programmer (not to the end-user), but very often not enough to locate the problem.

When you catch an error you have some choices:

  • repair the situation so the program can continue to run normally (as in the example above)
  • throw a new exception which the caller of the failing method then must handle
  • ignore the error (not recommended!)
  • pull the emergency break by calling System.exit()--probably after having written information to log files etc.

A really useful feature is the ability to create your own exception classes. This is done by creating a subclass of class "Exception". If you detect a problem in your application you may now throw one of your own exceptions. By doing this you simplify your error handling code, since you can now handle system errors and application errors in the same, consistent way.

So much for the basics.

When things go wrong - collect data!

I'll now describe a general technique, using your own exception classes, that can be used to handle severe, non-repairable errors. This means that your application has detected a situation that can not be neglected, so what's important now is this:

  1. collect as much information as possible about what has happened
  2. write this data to some persistent media--e.g. a log file or a data base
  3. give the user--assuming there is one--some explanatory information about what has happened
  4. keep the application alive if this makes sense and you're sure that this will not introduce further damage

The reason for "1" and "2" is obvious: in order for the support people to be able to find out what went wrong, so a program bug can be fixed, and to be able to tell the user what has happened and what the consequences are, you need all the information that you can get. We have all experienced the frustration by receiving error message like "System error at unknown location". If this is all the information the support people get, then it might be impossible to locate the problem.

So how do we collect data in a systematic way?

Let's consider the general situation where your "top-level" program (which could be a servlet, a JSP-page, or any Java class) calls method "a" in class "A", which again calls method "b" in class "B", where an exception is thrown. Let's for simplicity limit the example to these three levels.

What we should do when the exception in "b" is thrown is this:

  1. let "b" catch the exception
  2. let the catch-code save all essential data in our own exception class (see the specs below) and...
  3. throw this exception
  4. let "a" catch it
  5. let the catch-code in "a" save its own essential data in a new instance of our own exception class and...
  6. throw this exception
  7. let the top-level program catch it
  8. this program should now ensure that all collected data is written to the proper log files, and
  9. give the user at the PC an understandable message of what's going on

 

How to Add Java Applets to Your Site

New on the Java Boutique:

New Review:

Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling API boasts simplicity, ease-of-integration, a well-rounded feature set, and it's free!

New Applet:

Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA sequences into three useful formats.

Elsewhere on internet.com:

WebDeveloper Java
Lots of Java information on webdeveloper.com

WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.

ScriptSearch Java
Hundreds of free Java code files to download.

jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.

 Avaya DevConnect Center
 Service Component Architecture/Service Data Objects Solution Center
 Intel Go Parallel Portal
 Internet.com eBook Library
 IBM Software Construction Toolbox
 Microsoft RIA Development Center
 Destination .NET
XML error: not well-formed (invalid token) at line 53
advertisement
Receive Articles via our XML/RSS feed
Receive Articles via our XML/RSS feed

JavaBytes
Internet Cyclone
This powerful, easy-to-use, internet optimizer is for Windows 95, 98, ME, NT, 2000 and XP. It's designed to automatically optimize your Windows settings, boosting your Internet connection up to 200%.

Metasploit 3.2 Offers More 'Evil Deeds'
'Thank You Apple. Seriously.'
The Buzz: BlackBerry App Store Seen Next
Is .NET on Linux Finally Ready?
Red Hat Takes on HPC Market, Microsoft
Python's New Release Bridges the Gap
No Flash Seen on iPhone Horizon
Apple Yields to Complaints Over iPhone NDA
Microsoft Shows Some Ankle With Visual Studio
Gentoo Linux Cancels Distribution

Use Explicit Conversion Functions to Avert Reckless Implicit Conversions
Polyglot Programming: Building Solutions by Composing Languages
Automated testing for .NET by Ben Hall
"Supply Chain" SOA with SKOS
Service Component Architecture in Real Life
C++Ox: The Dawning of a New Standard
Getting Started with Virtualization
Master Complex Builds with MSBuild
eCryptfs: Single-File Encryption in Linux
CCXML in Action: A CCXML Auto Attendant

Advertising Info  |   Member Services  |   Contact Us  |   Help  |   Feedback  |   Site Map  |   Network Map  |   About



JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
IBM Whitepaper: Innovative Collaboration to Advance Your Business
Internet.com eBook: Real Life Rails
Avaya Article: Call Control XML - Powerful, Standards-Based Call Control
Internet.com eBook: The Pros and Cons of Outsourcing
Go Parallel Article: Scalable Parallelism with Intel(R) Threading Building Blocks
Internet.com eBook: Best Practices for Developing a Web Site
IBM CXO Whitepaper: The 2008 Global CEO Study "The Enterprise of the Future"
Avaya Article: Call Control XML in Action - A CCXML Auto Attendant
Go Parallel Article: James Reinders on the Intel Parallel Studio Beta Program
IBM CXO Whitepaper: Unlocking the DNA of the Adaptable Workforce--The Global Human Capital Study 2008
Adobe Acrobat Connect Pro: Web Conferencing and eLearning Whitepapers
Go Parallel Article: Getting Started with TBB on Windows
HP eBook: Storage Networking , Part 1
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Go Parallel Video: Intel(R) Threading Building Blocks: A New Method for Threading in C++
HP Video: Is Your Data Center Ready for a Real World Disaster?
Microsoft Partner Portal Video: Microsoft Gold Certified Partners Build Successful Practices
HP On Demand Webcast: Virtualization in Action
Go Parallel Video: Performance and Threading Tools for Game Developers
Rackspace Hosting Center: Customer Videos
Intel vPro Developer Virtual Bootcamp
HP Disaster-Proof Solutions eSeminar
HP On Demand Webcast: Discover the Benefits of Virtualization
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Microsoft Download: Silverlight 2 Software Development Kit Beta 2
30-Day Trial: SPAMfighter Exchange Module
Red Gate Download: SQL Toolbelt
Iron Speed Designer Application Generator
Microsoft Download: Silverlight 2 Beta 2 Runtime
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
IBM IT Innovation Article: Green Servers Provide a Competitive Advantage
Microsoft Article: Expression Web 2 for PHP Developers--Simplify Your PHP Applications
Featured Algorithm: Intel Threading Building Blocks - parallel_reduce
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES