File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes OO, Patterns, UML and Refactoring and the fly likes Exceptions pollute my code Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Engineering » OO, Patterns, UML and Refactoring
Bookmark "Exceptions pollute my code" Watch "Exceptions pollute my code" New topic
Author

Exceptions pollute my code

Vladas Razas
Ranch Hand

Joined: Dec 02, 2003
Posts: 385
When any of my classes needs to throw exception, I define exception class. I try use "build-in" exceptions as much as I can (IllegalStateException and InvalidArgumentException are my best friends) still there are lots of custom ones. They do not do anything they are just derrived from Exception. The only reason because caller can do "catch (thisWrong), catch (thatWrong).

Does anyone has/uses elegant solution instead of deriving multiple do-nothing exception classes? What about putting exception classes inside the class that throws them?
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
I tend to write custom exceptions, too, but I don't experience an explosion of exceptions that bloat my code. I wonder what you do differently.

Can you show us an typical example of what you use exceptions for?


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Sathya Srinivasan
Ranch Hand

Joined: Jan 29, 2002
Posts: 379
Someone told me that trhe Spring Framework uses a lot of RuntimeExceptions (not derived from Exception and hence, need not be checked). I personally haven't looked into that approach. You might probably be interested in a similar approach.

I guess the general rule is 'use RuntimeException (or customized subclass of it) whenever you can and Exception only when it is absolutely essential'.


Cheers, Sathya Srinivasan - SCJP 1.2, SCWCD 1.2, SCMAD 1.0
Co-Author of Whizlabs SCMAD Certification Exam Simulator and SCMAD Exam Guide Book
Vladas Razas
Ranch Hand

Joined: Dec 02, 2003
Posts: 385
Here is a typical class that may throw custom exceptions. I am 100% sure no other thing will need to throw those exceptions so I placed them inside the class. For now I am happy about it since I have 1 file not 4. As you can see those exceptions do not contain any specific code, just error message and of their type.

Vladas Razas
Ranch Hand

Joined: Dec 02, 2003
Posts: 385
There are people who love RuntimeException approach and others who say its tainted.

In case with only RuntimeExceptions we have to specify them for every method that throws them AND all runtime exceptions that may be thrown by methods it calls... Compiler will not help us here so we may miss some exception and it will pop-up to unsuspecting caller.

I've read somewhere why RuntimeException where introduced. They are faster and there are most common ones like NullPointerException that may be thrown by almost every method. So it would be very inconvenient not to use RuntimeException.

Still sometime RuntimeException must be used. I.e. EJB RemoteException. Also if we implement interface and our implementation must throw exception but interface doesn't have any specified.

Just my thoughts...
Sathya Srinivasan
Ranch Hand

Joined: Jan 29, 2002
Posts: 379
Vladas,

I am not sure you are creating the custom exceptions for the right reason. From what I understand from your example, you are creating a custom Exception class for each 'variation' of the exception that you are getting in the program. Why not simply throw an ApplicationException with a very specific String (which can be read from a Properties file)?

I normally tend to create custom exceptions only when I can have different system level exceptions for different implementations that mean the same thing from the app's perspective.

For example, if my program needs to read some stuff, it can throw an IOException if it is reading it from a file or it can throw an SQLException if it is reading it from a database. In such cases, I would create a generic DataAccessException which wraps the system-level exception.

Another situation might be if there is an algorithm-specific reason. I believe your intention is meant for the second reason, but I am not sure whether you need such classes.

One main question you need to ask when you are customizing exceptions is "What is my client application going to do with this exception? Is it going to have different behaviors if it catches different exceptions or is it simply going to print some message somewhere?".

If your answer to the first part is "Yes", then you need specific exception classes. If your answer to the second part is "Yes", then you need only one exception that has a nice, customizable String.
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
As an experiment in style I wrote my Wiki so that all public methods throw only WikiException which extends RuntimeException. Public methods never declare exceptions and most methods never catch them, but just let them bubble up. The only reason to catch one is if I'm going to take some an alternate path in the code, and most classes simply have no "recover from error" path. At the top levels of the architecture I catch them and present error messages to the user.

I have to say I was very pleased with the experiment. The code is largely free from try-catch and exception handling. Much easier to read!


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
I wonder how those Exceptions are used. I prefer to use Exceptions for programming errors and things that I can't check beforehand (such as IO errors). For everything else I'd rather let the code not call a method when it doesn't make sense.

For example, instead of



I'd rather have



Does that sound reasonable?
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
BTW, I I'd be concerned about an existing template being overwritten because of a programming error, I might add an

assert !this.contains(newTemplate);

to the beginning of the add method...
Vladas Razas
Ranch Hand

Joined: Dec 02, 2003
Posts: 385
This is application that reads data file and parses it into java objects, which are being used in the same app later. All those exceptions specify different error reason in the data xml file. Since the file is human formed XML, any of these can happen. That's an interesting point Stan suggested. Yes it's true - all those exceptions will lead to error message displayed to user. No recovery or different execution paths. Probably 1 exception would be well enough in my case. Still would you agree if that's a re-usable class it would make sense to throw different exceptions? Anyways I like that I placed exception inside the class if any other class doesn't throw it.

Thanks!
Vladas Razas
Ranch Hand

Joined: Dec 02, 2003
Posts: 385
I really like Stan's approach: making application wide runtime exception. It's very convenient. Later on, if we want to re-use class in other application we can then modify it with custom exceptions. Heh, but there is a drawback. I really like JUnit and I really test if correct exception is thrown. There is a problem - its hard to test this way when everything throws same exception with different message. Unless we test a message string being thrown. Maybe anybody has a better idea how to test that?

Regards
Sathya Srinivasan
Ranch Hand

Joined: Jan 29, 2002
Posts: 379
You can always store all the Strings in a property file and use only the keys in your application. That way you can check for the same key in your JUnit class also.
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Vladas Razas:
I really like JUnit and I really test if correct exception is thrown. There is a problem - its hard to test this way when everything throws same exception with different message.


Is it? Won't just all those tests test for the same exception, in different scenarios? Is there a problem with that?
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Another idea: It seems to me as if those errors actually don't need to hold you from going on parsing the XML?

In that case, instead of using exceptions you could use your own ValidationError objects and gather them in a Collecting Parameter.


if (templates.contains(newTemplate))
errors.add("duplicate template " + newTemplate);


After you parsed the whole XML, you can check wether some errors occured and show them to the user, or continue as usual.

Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Couple notes: I had to add one subclass of WikiException for file not found. It turned out this required different handling at a high level in the code so it had to know what kind of error happened.

I can see where you might expect an IO exception in a unit test and want to make sure you got one and not some parsing exception. But I'm having trouble adding exception types just for the unit tester when the real application really doesn't care what happened.

Hey, you know what? WikiException holds a reference to the root cause. I can walk the chain of nested exceptions and look for an IO exception!


I also have a log writer that writes to a circular buffer in memory so I can view the last "n" lines from the log online. I could scan that for IOException, too.
[ November 14, 2004: Message edited by: Stan James ]
Vladas Razas
Ranch Hand

Joined: Dec 02, 2003
Posts: 385
Thanks! I taken every reply into account. For my case parsing error should terminate program. It's human data file, but it is part of application configuration and should be edited by developer.

Sincere thanks!
Alexandru Popescu
Ranch Hand

Joined: Jul 12, 2004
Posts: 995
Originally posted by Ilja Preuss:
I wonder how those Exceptions are used. I prefer to use Exceptions for programming errors and things that I can't check beforehand (such as IO errors). For everything else I'd rather let the code not call a method when it doesn't make sense.


I do too think this is the correct way to handle the problem. Otherwise we would call exception driven programming (using exceptions to drive your code logic is in fact a higly commented programming error).

./pope


blog - InfoQ.com
Vladas Razas
Ranch Hand

Joined: Dec 02, 2003
Posts: 385
But yes, I think my case is just that. I parse application configuration file, which is not for user to edit. It is shipped as part of application. I think this is unexpected error if this file is wrong. And in my case application can't work without it.
Alexandru Popescu
Ranch Hand

Joined: Jul 12, 2004
Posts: 995
Being the case of a programming problem I would go the RuntimeException way .

./pope
Pradeep bhatt
Ranch Hand

Joined: Feb 27, 2002
Posts: 8919

Originally posted by Ali Pope:
Being the case of a programming problem I would go the RuntimeException way .

./pope


Is is true that C# has no checked exception? :roll:


Groovy
Alexandru Popescu
Ranch Hand

Joined: Jul 12, 2004
Posts: 995
Yep, C# doesn't have the notion of checked exception, so any exception in C# code is behaving as a unchecked exception in Java.

./pope
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Exceptions pollute my code