Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Exception handling

6 views
Skip to first unread message

Andre Rothe

unread,
Nov 27, 2009, 11:41:30 AM11/27/09
to
Hello!

I try to find some information about a best-practice exception
framework. Maybe this group can help me.

An application throws an exception within a low-level method, let us
say, within a database access layer. It has occured as reaction of a
wrong value given by the user. The method can throw the exception, the
next higher abstraction layer can rollback the associated database
operation and throw it up to the client application.

To code that, I can use a generalized exception class like
IllegalArgumentException, but also a detailled exception class like
WrongBirthdayException. If I use the first one, the client cannot give
a specific message to the user (because the method stores several
values and only one was wrong).

If I try the detailled exception I can use exception chaining or
translation to hide the low-level exception from the client. To achive
that, I could define a high-level exception within the interface of
the service, maybe ServiceException, which is a superclass of
WrongBirthdayException.

public void storeSomething() throws ServiceException;

But now I don't have enough information within the client application
to present a detailled message to the user. I know, there were a
ServiceException, but I have to use

a) instanceof to find the real sub-class or
b) getCause() to find the reason for the exception

If I specifiy the detailled exception WrongBirthdayException within
the service interface, I will have the correct reason for the
exception:

public void storeSomething() throws WrongBirthdayException;

try {
service.storeSomething();
} catch (WrongBirthdayException e) {
// do something
}

But such a service method can throw several exceptions (one for every
possible problem). So I would have a lot of possible exception classes
within the interface definition and a lot of several catch statements
within the client. Both will bloat my code.

public void storeSomething() throws
WrongBirthdayException,WrongNameException,WrongPostcodeException;

On the other hand I could use the generalized exception:

try {
service.storeSomething();
} catch (ServiceException e) {
handleIt(e);
}

private void handleIt(ServiceException e) {
if (e instanceof WrongBirthdayException) {

}
if (e instanceof WrongPostcodeException) {

}
// ...
}

but now I have to use a) or b) (see above) to find and to react on the
exception. Another possibility is to use the generalized exception to
reduce the code overhead within the interface but I could use the
detailled exception on the catch statement:

public void storeSomething() throws ServiceException {
throw new WrongBirthdayException();
}

try {
service.storeSomething();
} catch (WrongBirthdayException e) {

} catch (ServiceException e) {

}

But here I will get stomach ache, I use information about detailled
exception, which I don't get from the service interface definition.

A further method could be the definition of a detailled message string
direct within the service as part of a generalized exception class.
But there are two disadvantages: 1) the service can run with another
locale settings than the client; 2) sometimes you need programatic
access to the exception reason instead of simple logging/displaying
the message to change the code path.

Are there any best-practice solutions (patterns?) for this problem? I
would be happy about some links to examples or discussions.

Thanks a lot
Andre

markspace

unread,
Nov 27, 2009, 12:29:12 PM11/27/09
to
Andre Rothe wrote:

> A further method could be the definition of a detailled message string


This one is definitely not best practice. Avoid it at all costs.


> Are there any best-practice solutions (patterns?) for this problem? I
> would be happy about some links to examples or discussions.


I can't say I know best practice here, but some ideas do occur to me.


Don't forget that Java exception are just regular classes. Any time you
see a construct, for any class, like this:

if( object instanceof ClassA ) {
do something ...
} else if( object instanceof ClassB ) {
do something else...
} ... etc., lots more....

You should think polymorphism and overriding.

public interface ExceptionHandler {
void handler();
}

public abstract class DBFrameworkException
extends Exception
implements ExceptionHandler
{
ExceptionHandler handler;
void setHandler( ExceptionHandler h) {
handler = h;
}
@Override
void handler() {
if( handler != null ) {
handler.handler();
}
}
}

public class DataTypeMismatch extends DBFrameworkException
{
}

Now at least you don't have to check for lots of different classes. If
the class is "ExceptionHandler" you can just execute the handler
method... which might do different things based on the handler that was
installed.

Since the handler can be set, you can make a factory or registry of
handlers, and inject the behavior into the lower layers. No need to
specify at compile time or hard code it, just look for the handler and
install one if it exists. If none exist, maybe an default handler that
just writes to the logger would be appropriate.

This allows you to use fewer classes--you only need one exception class,
really. And you only need as many handlers as you have different
behaviors. No more than you'd have to write in your big ol' if-else
stack you had.


Jean-Baptiste Nizet

unread,
Nov 27, 2009, 12:58:00 PM11/27/09
to
Andre Rothe a �crit :

>
> public void storeSomething() throws WrongBirthdayException;
>
> try {
> service.storeSomething();
> } catch (WrongBirthdayException e) {
> // do something
> }
>
> But such a service method can throw several exceptions (one for every
> possible problem). So I would have a lot of possible exception classes
> within the interface definition and a lot of several catch statements
> within the client. Both will bloat my code.
>

User input validation should be performed before the call to
service.storeSomething(). Of course, you should program storeSomething
in a defensive way, and verify in the service method that its contract
is fulfilled by the caller, but then an IllegalArgumentException will do
fine.

In pseudo-code, instead of doing
1. accept input from the user
2. call the service
3. catch an exception from the service
4. display errors to the user

you should do

1. accept input from the user
2. validate the input
3. display errors to the user if any
4. if no error, call the service
5. if the service throws an exception, then your validation logic at
step 2 has a bug.

If the service is the only component being able to perform the
validation logic for any reason (for example, the validation logic
depends on values fetched or computed in the service method itself),
then you might use a rich ValidationException, containing, for example,
a list of validation errors. Each validation error would contain a
message key and some arguments of the error message, which would be
displayed in an internationalized way by the presentation layer.

JB.

Andre Rothe

unread,
Nov 27, 2009, 1:42:14 PM11/27/09
to
Hello!

It was only a simple example to construct the problem. Often I cannot
validate the user input on that way, it is possible to get input from
other applications or components, so it is your component, which has
to check the input on the deepest level. Your own component must not
be a database access, but it is on your turn to throw exceptions back
to the other unchangeable components of the system.

Thanks
Andre

On Nov 27, 6:58 pm, Jean-Baptiste Nizet <jnizetNOS...@NOSPAMfree.fr>
wrote:

Andre Rothe

unread,
Nov 27, 2009, 1:53:15 PM11/27/09
to
On Nov 27, 6:29 pm, markspace <nos...@nowhere.com> wrote:
> Andre Rothe wrote:
> > A further method could be the definition of a detailled message string
>
> This one is definitely not best practice.  Avoid it at all costs.

Yes, I have added it for completeness :-)

> Now at least you don't have to check for lots of different classes.  If
> the class is "ExceptionHandler" you can just execute the handler
> method... which might do different things based on the handler that was
> installed.

Oh, I understand. I can use the exceptions of the service to build
another object instance within the client, which implements the
interface ExceptionHandler. This could be useful, I will think about
it.

> Since the handler can be set, you can make a factory or registry of
> handlers, and inject the behavior into the lower layers.  No need to
> specify at compile time or hard code it, just look for the handler and
> install one if it exists.  If none exist, maybe an default handler that
> just writes to the logger would be appropriate.
>
> This allows you to use fewer classes--you only need one exception class,
> really.  And you only need as many handlers as you have different
> behaviors.  No more than you'd have to write in your big ol' if-else
> stack you had.

This would be nice, if I can integrate it into the system, I will try
it.
Client and service are not on the same machine, so it could be hard to
implement it, but this is a challange for me :-)

Thanks
Andre

Pitch

unread,
Nov 27, 2009, 2:06:30 PM11/27/09
to
In article <c99d8536-8e8c-4e2f-8c08-8a58d72e9649
@k17g2000yqh.googlegroups.com>, aro...@phosco.info says...

> ...


These are my general rules:

- layer X catches everything but RuntimeExceptions and throws
"X_Exception"

- layer Y catches everything but RuntimeExceptions and throws
"Y_Exception"

- GUI/presentation/interface layer catches everything and logs it or
displays a dialog or whatever.

- exceptions to these rules exists and depend on the case, especially if
RuntimeExceptions are to be ignored or not


When I say layer X I mean the interface/methods of that layer.

Rules inside a layer of abstraction:

- If it has to do with possible error in my business logic it throws
MyException, else it bubbles up whatever happened

- If there are several modules in a leyer, each can have its own
"ModuleException" which extends "LayerException"


HTH


--
stirr your cofee properly

Tom Anderson

unread,
Nov 27, 2009, 3:06:54 PM11/27/09
to
On Fri, 27 Nov 2009, Pitch wrote:

> These are my general rules:
>
> - layer X catches everything but RuntimeExceptions and throws
> "X_Exception"
>
> - layer Y catches everything but RuntimeExceptions and throws
> "Y_Exception"
>
> - GUI/presentation/interface layer catches everything and logs it or
> displays a dialog or whatever.

This is pretty much the Right Way To Do It.

But note that in this case, you have to be careful about using
IllegalArgumentException, as it's a RuntimeException. If code in a deep
layer is doing input validation (say, taking a user-entered string and
looking something up in a database with it), then failure of validation
needs to be signalled with a checked layer-specific exception, otherwise
it will go through the upper layers and annoy the user.

On the other hand, if validation fails for a reason which could have been
caught by an upper layer (a parameter is null, an argument is too long or
the wrong colour, etc), then that's a programming error on the part of the
upper layer, and it's okay to throw an IllegalArgumentException. Although
it might still be wise to throw a checked exception.

tom

--
... including a depiction of evolution that would make a furious Charles
Darwin eat his own beard. -- Ben Croshaw, on Spore

Daniel Pitts

unread,
Nov 27, 2009, 7:14:36 PM11/27/09
to
Andre Rothe wrote:
> Hello!
>
> I try to find some information about a best-practice exception
> framework. Maybe this group can help me.
>
> An application throws an exception within a low-level method, let us
> say, within a database access layer. It has occured as reaction of a
> wrong value given by the user. The method can throw the exception, the
> next higher abstraction layer can rollback the associated database
> operation and throw it up to the client application.
This is a bad pattern.

The low-level methods should through exceptions which indicate
programmer error. Higher-level methods should validate *before* calling
lower-level methods. The high-level methods can either throw
appropriate exceptions or directly report problems to the user.

The reason I advocate this pattern is because Low-Level methods
shouldn't know or care whether their invocation is due to a user action,
or an automated process, or something else.

Low-Level methods should be designed to report programmer errors and
low-level interface problems (IO errors, DB errors, etc...)

Higher level methods should be task oriented (for example, "User
requested a record") The higher level method should verify that the
user entered valid data, and that the record was returned correctly.

It may seem like a little bit of repeating yourself, but once you
realize that the lower-level exception has a different purpose, you can
get over the fact that you might write the same check in two places.

To avoid the duplication of "checks", you can create a predicate method
somewhere that can be called by the lower-level method and the higher
level method. In the lower-level method, you can document in the
contract that the precondition is "isValidFoo()" (for example). This
makes it a programmer error to call a method with a bad precondition.

Now, if the lower-level method throws an exception, it can be of three
kinds: High-Level Programmer error (bug: failed to verify
precondition), Low-Level Programmer Error (bug: in the library),
Exceptional Circumstance (i.e. IOException). The first two should be
reported to the user only as "There was an internal error handling your
request", and the full stack-trace logged somewhere for reporting and
reproducing. The latter exception can be reported to the user with an
appropriate message (eg. "Unable to communicate with database", or
"Unable to open file")

Of course, this is all idealized. Sometimes it is infeasible to verify
user-input before calling the lower-level method. In which case, the
lower-level method can still throw a "low-level" exception, but it
should still be translated into "high-level" message by the higher level
code.

I hope this all makes sense. I could go on further, but if I go on any
longer and I'll have to break it into sections, gather references, add
markup, throw and catch exceptions, etc... ;-)

Lew

unread,
Nov 27, 2009, 7:32:37 PM11/27/09
to
Pitch wrote:
>> These are my general rules:
>>
>> - layer X catches everything but RuntimeExceptions and throws
>> "X_Exception"
>>
>> - layer Y catches everything but RuntimeExceptions and throws
>> "Y_Exception"
>>
>> - GUI/presentation/interface layer catches everything and logs it or
>> displays a dialog or whatever.

Tom Anderson wrote:
> This is pretty much the Right Way To Do It.
>
> But note that in this case, you have to be careful about using
> IllegalArgumentException, as it's a RuntimeException. If code in a deep
> layer is doing input validation (say, taking a user-entered string and
> looking something up in a database with it), then failure of validation
> needs to be signalled with a checked layer-specific exception, otherwise
> it will go through the upper layers and annoy the user.
>
> On the other hand, if validation fails for a reason which could have
> been caught by an upper layer (a parameter is null, an argument is too
> long or the wrong colour, etc), then that's a programming error on the
> part of the upper layer, and it's okay to throw an
> IllegalArgumentException. Although it might still be wise to throw a
> checked exception.

tom's advice jibes with what I've read from the pundits, that unchecked
exceptions generally correspond to programmer error and checked exceptions to
environmental issues or other failures outside programmer control, such as a
dropped connection.

--
Lew

Arne Vajhøj

unread,
Nov 27, 2009, 8:40:49 PM11/27/09
to
Daniel Pitts wrote:

> Andre Rothe wrote:
>> I try to find some information about a best-practice exception
>> framework. Maybe this group can help me.
>>
>> An application throws an exception within a low-level method, let us
>> say, within a database access layer. It has occured as reaction of a
>> wrong value given by the user. The method can throw the exception, the
>> next higher abstraction layer can rollback the associated database
>> operation and throw it up to the client application.
> This is a bad pattern.
>
> The low-level methods should through exceptions which indicate
> programmer error. Higher-level methods should validate *before* calling
> lower-level methods.

That is not always possible.

> Of course, this is all idealized. Sometimes it is infeasible to verify
> user-input before calling the lower-level method. In which case, the
> lower-level method can still throw a "low-level" exception, but it
> should still be translated into "high-level" message by the higher level
> code.

Yep.

Arne

Roedy Green

unread,
Nov 28, 2009, 1:17:32 AM11/28/09
to
On Fri, 27 Nov 2009 08:41:30 -0800 (PST), Andre Rothe
<aro...@phosco.info> wrote, quoted or indirectly quoted someone who
said :

>Are there any best-practice solutions (patterns?) for this problem? I
>would be happy about some links to examples or discussions.

Don't catch an exception unless you can effectively neutralise it.
Otherwise, leave it for higher levels to deal with.

To make it easier for higher levels, it is sometimes a good thing to
catch a low level exception and rethrow a higher level
more-application specific one.
--
Roedy Green Canadian Mind Products
http://mindprod.com
I mean the word proof not in the sense of the lawyers, who set two half proofs equal to a whole one, but in the sense of a mathematician, where half proof = 0, and it is demanded for proof that every doubt becomes impossible.
~ Carl Friedrich Gauss

Andre Rothe

unread,
Nov 28, 2009, 4:12:20 AM11/28/09
to
Hi,

I think, this will not work in every case. If you have a user
management system, which allows the user to change his password
and which forces the user to change his password after some
days (a simple example).

A password service provides two methods:

void changePasssword(String old, String new);
Session login(String user, String password);

The service has access to a database, which stores the user.
This simple example has a lot of possibilities to throw
exceptions.

First, you have a database access layer. It can throw
SQLException, which I would catch there and translate
into my own LowLevelSQLException. If I would use your
suggestion I would have a single exception for all
SQLExceptions.

How I would get programmatic access to the real reason
behind LowLevelSQLException? I can lose the connection,
which should be handled by cleanup of some resources but
I can also have a problem with the database structure,
which is a programmer error. So I have to divide it into
two exceptions. The first one I have to handle within the
service (but I have to notify the user), the second one
I should log and notify the user.

Another problem is a locked acount, the password has not
been changed for a long time. A login would generate an
exception, maybe AccountLockedException. If the account
isn't locked yet, the method can generate a
PasswordMustChangeException to notify the client. The
client application would display a dialog which lets the
user enter a new password. It wouldn't display a simple
output dialog which shows the error, the client must
react on the special exception.

The changePassword() method has also several possibilities
to throw an exception. There could be multiple password
policies which throw an exception: PasswordEmptyException,
PasswordTooShortException, PasswordMustContainLetterException.
There can also be an exception, if the user has given a wrong
old password (WrongPasswordException).

I wouldn't return such status values as return values,
I would use exceptions. But I have to react on the client
on the specific exception, every time the client must decide,
which dialog must be displayed.

Back to the exception framework. I can write this:

public void changePassword() throws PasswordEmptyException,
PasswordTooShortException, PasswordMustContainLetterException,
WrongPasswordException;

To prevent such a dependency (I can have more policies later),
I would use a superclass of the exceptions above, like
PasswordException.

public void changePassword() throws PasswordException;

Now I have the described problem: I know there were a
PasswordException,
But I don't know, what I have to display to the user within the
client.
I also could differ between PasswordPolicyException and
WrongPaswordException, but I cannot open a specific dialog for the
wrong policy.

So I have to use a long instanceof or getClause() construct to find
the right reason. Or I can use a unique error number within the
exception
and a switch-case to split the execution pathes.

A simple layer-X-throws-exception-X model will not work, I think.
The handler idea of markspace can be a solution, but I need the
handler
on the creation time of the exception. Or I have to use a factory
which provides a method for every service exception.

Too much possibilites...
Andre

Arved Sandstrom

unread,
Nov 28, 2009, 9:04:26 AM11/28/09
to
Andre Rothe wrote:
> Hi,
>
> I think, this will not work in every case. If you have a user
> management system, which allows the user to change his password
> and which forces the user to change his password after some
> days (a simple example).
>
> A password service provides two methods:
>
> void changePasssword(String old, String new);
> Session login(String user, String password);
>
[ SNIP ]

> Back to the exception framework. I can write this:
>
> public void changePassword() throws PasswordEmptyException,
> PasswordTooShortException, PasswordMustContainLetterException,
> WrongPasswordException;
>
> To prevent such a dependency (I can have more policies later),
> I would use a superclass of the exceptions above, like
> PasswordException.
>
> public void changePassword() throws PasswordException;
>
> Now I have the described problem: I know there were a
> PasswordException,
> But I don't know, what I have to display to the user within the
> client.

[ SNIP ]

I don't see the specific problem here. You've got a number of exceptions
that you can throw, all of which are subclasses of a more general one.
When you throw the more general exception, PasswordException in this
case, you use the ctor that takes a Throwable as an argument. So no loss
of information.

On the other end, it's good practise to unwind an exception that you're
handling to determine the real root cause Throwable. Once you've got it,
the suggested handler idea could be used if that makes sense for the
specific client situation. In any case you will definitely know what
exact exception was originally generated.

AHS

markspace

unread,
Nov 28, 2009, 1:39:34 PM11/28/09
to
I'm not sure, but it seems to me that you are mixing too much knowledge
of other layers here. You want to keep each layer self-contained.

For example, if you loose a connection, clean up and retry the
connection in the lower level database layer. Make a "best effort" to
delivery the query. If some number of retries fails (maybe just one
retry), then you have a real issue and should throw an exception, but
the higher level layer doesn't know or care why, it just shows "The
database is down, please try again later" to the user.

On the other hand, the problem with changing a stale password seems like
something the application itself should model, not the lower level
database. You could add a method "boolean isPasswordMustChange()"
method, or you could add "throws PasswordMustChangeException" to the
login() method. Both are equivalent. Both are part of the public API.
Not checking one is an application (and programmer) error.

It's OK to enforce the password policy with a low-level database trigger
or something similar, but the application should behave as if it's the
one that handles all of that logic.

The trick is to get the right information, return values or exceptions,
to the right layer, and then just handle them appropriately. You'd
never want to handle all errors in any one layer. That would be a
confusing job at best, unless they were handled completely generically
(i.e., the Java Logging API, which does use a factory pattern, btw).


More comments interspersed with yours below....


Andre Rothe wrote:

> A password service provides two methods:
>
> void changePasssword(String old, String new);
> Session login(String user, String password);
>

> How I would get programmatic access to the real reason


> behind LowLevelSQLException? I can lose the connection,
> which should be handled by cleanup of some resources but
> I can also have a problem with the database structure,
> which is a programmer error. So I have to divide it into
> two exceptions. The first one I have to handle within the
> service (but I have to notify the user), the second one
> I should log and notify the user.


Don't. Log it. Programmers should test their code before release. If
they haven't, then they'll have to read the logs to determine why their
code failed in the field. A few trips to a frozen machine room far away
from civilization will be a good incentive for them to test better.


>
> Another problem is a locked acount, the password has not
> been changed for a long time. A login would generate an
> exception, maybe AccountLockedException. If the account
> isn't locked yet, the method can generate a
> PasswordMustChangeException to notify the client. The
> client application would display a dialog which lets the
> user enter a new password. It wouldn't display a simple
> output dialog which shows the error, the client must
> react on the special exception.


I'd prefer that you add a method, or that the app just check if the
password is old and require the user to change it on its own. If the
programmer forgets to do this, just throw a low level database
exception, and log it. More trips to a cold machine room, and soon the
programmers will start to see the value of an adequate test harness.


>
> The changePassword() method has also several possibilities
> to throw an exception. There could be multiple password
> policies which throw an exception: PasswordEmptyException,
> PasswordTooShortException, PasswordMustContainLetterException.
> There can also be an exception, if the user has given a wrong
> old password (WrongPasswordException).


These should all be validated by the application first. If the app
forgets, then they can be logged as a low level db exception. Tell your
coders to learn to read the spec.

You appear to be trying to get the application to automagically adjust
to whatever the DB is enforcing at the moment. After a while, systems
become complex enough that you have to nail some behaviors down with a
written spec, and then don't change them until you've got at least one
version working and shipped. Decide on a password policy, and have both
the app and the DB enforce it independently.

You also mentioned something about having two separate systems. Note
that transmitting a password in clear text is almost always a serious
security concern. I hope your transmissions are encrypted.


Andre Rothe

unread,
Nov 28, 2009, 3:58:07 PM11/28/09
to
On Nov 28, 7:39 pm, markspace <nos...@nowhere.com> wrote:
> I'm not sure, but it seems to me that you are mixing too much knowledge
> of other layers here.  You want to keep each layer self-contained.

Maybe. I have tried it.

> For example, if you loose a connection, clean up and retry the
> connection in the lower level database layer.  Make a "best effort" to
> delivery the query.  If some number of retries fails (maybe just one
> retry), then you have a real issue and should throw an exception, but
> the higher level layer doesn't know or care why, it just shows "The
> database is down, please try again later" to the user.

Exactly what I have. The client must invalidate the current user
session and logs off the user.

> On the other hand, the problem with changing a stale password seems like
> something the application itself should model, not the lower level
> database.  You could add a method "boolean isPasswordMustChange()"
> method, or you could add "throws PasswordMustChangeException" to the
> login() method.  Both are equivalent.  Both are part of the public API.
> Not checking one is an application (and programmer) error.

I have decided to move it into the core system, because it is used by
several applications (clients), so I would have to program it several
times.
To prevent that, it is part of the core.

> It's OK to enforce the password policy with a low-level database trigger
> or something similar, but the application should behave as if it's the
> one that handles all of that logic.

The application should get enough information to display the right
error
message and to show the change password dialog again.

> The trick is to get the right information, return values or exceptions,
> to the right layer, and then just handle them appropriately.  You'd

Right. Thats one of my problems, which I try to solve with a pattern
or
best-practice-approach.

> never want to handle all errors in any one layer.  That would be a
> confusing job at best, unless they were handled completely generically
> (i.e., the Java Logging API, which does use a factory pattern, btw).

Thanks, I will check the source, to get more answers...

> Andre Rothe wrote:
> > A password service provides two methods:
>
> > void changePasssword(String old, String new);
> > Session login(String user, String password);
>
> > How I would get programmatic access to the real reason
> > behind LowLevelSQLException? I can lose the connection,
> > which should be handled by cleanup of some resources but
> > I can also have a problem with the database structure,
> > which is a programmer error. So I have to divide it into
> > two exceptions. The first one I have to handle within the
> > service (but I have to notify the user), the second one
> > I should log and notify the user.
>
> Don't.  Log it.  Programmers should test their code before release.  If
> they haven't, then they'll have to read the logs to determine why their
> code failed in the field.  A few trips to a frozen machine room far away
> from civilization will be a good incentive for them to test better.

LOL, but I should notify the user, that something is wrong and the
current operation hasn't been finished. Ok, the message shouldn't
contain
the complete SQL statement...

> > Another problem is a locked acount, the password has not
> > been changed for a long time. A login would generate an
> > exception, maybe AccountLockedException. If the account
> > isn't locked yet, the method can generate a
>

> I'd prefer that you add a method, or that the app just check if the
> password is old and require the user to change it on its own.  If the
> programmer forgets to do this, just throw a low level database
> exception, and log it.  More trips to a cold machine room, and soon the
> programmers will start to see the value of an adequate test harness.

I have decided to move this part in the Core too. It allows me to
throw
an exception in every case, the programmer of the client must catch
the exception only and shows a dialog. The application should be thin.

> > The changePassword() method has also several possibilities
> > to throw an exception. There could be multiple password
> > policies which throw an exception: PasswordEmptyException,
> > PasswordTooShortException, PasswordMustContainLetterException.
> > There can also be an exception, if the user has given a wrong
> > old password (WrongPasswordException).
>
> These should all be validated by the application first.  If the app
> forgets, then they can be logged as a low level db exception.  Tell your
> coders to learn to read the spec.

Same as above, I try to keep the application thin, because several
applications will use the core system. So I have to provide a lot
of detailled exception from the core to the clients and must react
on these within the client.

> You appear to be trying to get the application to automagically adjust
> to whatever the DB is enforcing at the moment.  After a while, systems

Right. That's the main focus. The core system can be widely
configured
and the application has to react on all those changes.

At the moment I have about 1000 positions where I have to create
exceptions
within the core.
I think, this is the right point to think about a generalized
exception
handling. The current method is very ugly and therefore I try to find
a method to make things better.

> You also mentioned something about having two separate systems.  Note
> that transmitting a password in clear text is almost always a serious
> security concern.  I hope your transmissions are encrypted.

Yepp, the core and clients communicate per RMI, secured by SSL.

I have created a test system, which uses a factory now. At the moment
I create detailled exceptions within the core (i.e.
PasswordTooShortException),
but I bubble up these exceptions as more generalized exceptions
(i.e. PasswordException), which is an abstract class and superclass of
PasswordTooShortException. I use abstract classes to prevent
instantiation,
because they don't specify an error status, they group detailled
exceptions
only.

On the core interface I translate the PasswordException into a
CoreException
and re-throw it to the client. The core interface contains only
"throws CoreException". So I have to catch these exceptions within
the
clients:

try {
core.login();
} catch(CoreException e) {
// handle it
}

which simplifies the code a lot. With e.getCause() I can access the
reason of
the exception, but only as Throwable. The handler factory must use a
long
list of instanceof to find the correct handler implementation, which
is ugly.
Maybe the factory can act as a manager, I would have to register all
handlers.
The factory would ask every handler, whether or not it can handle the
given
exception:

public class WrongPasswordExceptionHandler implements ExceptionHandler
{

public static boolean accept(Throwable e) {
return (e instanceof WrongPasswordException);
}

}

This allows me to add more handlers dynamically, but it has a
disadvantage.

I have to prepare the factory for almost every class to access the
right
handlers within the right context (same exception can be processed by
different handlers for different parts of the application).

And I can run into problems, if I have to use different handlers for
a
single client class (two or more methods catch the same exception but
must handle it on different ways). There I must prepare such a
factory
just before the try-catch-statement which will pollute my client code
again.

Maybe I can extend the accept() method with class and method name,
which I could get from the call stack...

Andre

Daniel Pitts

unread,
Nov 29, 2009, 8:19:40 PM11/29/09
to
Daniel Pitts wrote:
> Andre Rothe wrote:
>> Hello!
>>
>> I try to find some information about a best-practice exception
>> framework. Maybe this group can help me.
>>
>> An application throws an exception within a low-level method, let us
>> say, within a database access layer. It has occured as reaction of a
>> wrong value given by the user. The method can throw the exception, the
>> next higher abstraction layer can rollback the associated database
>> operation and throw it up to the client application.
> This is a bad pattern.
>
> The low-level methods should through exceptions which indicate
> programmer error. Higher-level methods should validate *before* calling
> lower-level methods. The high-level methods can either throw
> appropriate exceptions or directly report problems to the user.

I have written more about this in a blog post:
<http://virtualinfinity.net/wordpress/program-design/2009/11/29/levels-of-error-handling/>

--
Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>

Pitch

unread,
Nov 29, 2009, 8:58:08 PM11/29/09
to
In article <alpine.DEB.1.10.0...@urchin.earth.li>,
tw...@urchin.earth.li says...

>
> On Fri, 27 Nov 2009, Pitch wrote:
>
> > These are my general rules:
> >
> > - layer X catches everything but RuntimeExceptions and throws
> > "X_Exception"
> >
> > - layer Y catches everything but RuntimeExceptions and throws
> > "Y_Exception"
> >
> > - GUI/presentation/interface layer catches everything and logs it or
> > displays a dialog or whatever.
>
> This is pretty much the Right Way To Do It.
>
> But note that in this case, you have to be careful about using
> IllegalArgumentException, as it's a RuntimeException. If code in a deep
> layer is doing input validation (say, taking a user-entered string and
> looking something up in a database with it), then failure of validation
> needs to be signalled with a checked layer-specific exception, otherwise
> it will go through the upper layers and annoy the user.
>
> On the other hand, if validation fails for a reason which could have been
> caught by an upper layer (a parameter is null, an argument is too long or
> the wrong colour, etc), then that's a programming error on the part of the
> upper layer, and it's okay to throw an IllegalArgumentException. Although
> it might still be wise to throw a checked exception.

all good points, thanks

Pitch

unread,
Nov 29, 2009, 9:39:48 PM11/29/09
to
In article <9bf1619a-839e-4600-b628-80ed83aa74b6
@d10g2000yqh.googlegroups.com>, pho...@gmx.de says...


> void changePasssword(String old, String new);
> Session login(String user, String password);
>
> The service has access to a database, which stores the user.
> This simple example has a lot of possibilities to throw
> exceptions.
>
> First, you have a database access layer. It can throw
> SQLException, which I would catch there and translate
> into my own LowLevelSQLException. If I would use your
> suggestion I would have a single exception for all
> SQLExceptions.

If the database access is part of the password-service you can construct

new PasswordException(sqlException)

If you intend to clean-up afterwards, you do it in the db-layer, in a
try-finally, not in the password-service.

> How I would get programmatic access to the real reason
> behind LowLevelSQLException?

inheritance, see below


> Another problem is a locked acount, the password has not
> been changed for a long time. A login would generate an
> exception, maybe AccountLockedException. If the account
> isn't locked yet, the method can generate a
> PasswordMustChangeException to notify the client. The
> client application would display a dialog which lets the
> user enter a new password. It wouldn't display a simple
> output dialog which shows the error, the client must
> react on the special exception.

If login() method is part of the password-service and it throws
AccountLockedException, this exception should also extended from
PasswordException, ok?


Now, what you need to do is to extend everything else also from
PasswordException, so don't use getCause() but use inheritance. Then if
you need to reopen a dialog when you get PasswordEmptyException or
PasswordMustContainLetterException you catch those exceptions and let
everything else go up (or show a different dialog)


Basically, you have one main service/layer exception
(PasswordExceptino). All exceptions produced by the internal logic of
that layer (invalid password/account) extend form that main eception. If
layer receives external exceptions (SQLException) it wraps them up in
the main exception as the cause. That external exception should be
handled in the external layer but information could be presented to the
user, perhaps in an abstract message "External exception occurred". Each
kind of internal exception provide tho GUI layer a way to change program
execution in the way as suitable (error-dialog, reopen login dialog,
etc..).

Lew

unread,
Nov 29, 2009, 10:29:13 PM11/29/09
to
Andre Rothe said:
>> How I would get programmatic access to the real reason
>> behind LowLevelSQLException?

Pitch wrote:
> inheritance, see below

It could be said that chained exceptions are a better choice.

/** Throwable chainer.
* @param trow Throwable to chain.
* @param log Logger with which to log the chain.
*/
public static void chain( Throwable trow, Logger log )
{
for ( Throwable last = null, thr = trow;
thr != null && thr != last;
thr = (last = thr).getCause() )
{
log.debug( thr.getLocalizedMessage() );
}
}

--
Lew

Pitch

unread,
Nov 30, 2009, 5:32:18 AM11/30/09
to
In article <heve6b$p6k$1...@news.albasani.net>, no...@lewscanon.com says...


I don't get this. If you are just trying to log all causes, why not use
logger?

Lew

unread,
Nov 30, 2009, 9:39:13 AM11/30/09
to

Lew wrote:
>> It could be said that chained exceptions are a better choice.
>>
>> /** Throwable chainer.
>> * @param trow Throwable to chain.
>> * @param log Logger with which to log the chain.
>> */
>> public static void chain( Throwable trow, Logger log )
>> {
>> for ( Throwable last = null, thr = trow;
>> thr != null && thr != last;
>> thr = (last = thr).getCause() )
>> {
>> log.debug( thr.getLocalizedMessage() );
>> }
>> }

Pitch wrote:
> I don't get this. If you are just trying to log all causes, why not use
> logger?

A) this does use a logger, and B) the purpose isn't to show logging but chaining.

If you think I was "just trying to log all causes" then you missed the point.

--
Lew

Pitch

unread,
Nov 30, 2009, 10:17:18 AM11/30/09
to
In article <hf0leh$kob$1...@news.albasani.net>, no...@lewscanon.com says...

>
> Lew wrote:
> >> It could be said that chained exceptions are a better choice.
> >>
> >> /** Throwable chainer.
> >> * @param trow Throwable to chain.
> >> * @param log Logger with which to log the chain.
> >> */
> >> public static void chain( Throwable trow, Logger log )
> >> {
> >> for ( Throwable last = null, thr = trow;
> >> thr != null && thr != last;
> >> thr = (last = thr).getCause() )
> >> {
> >> log.debug( thr.getLocalizedMessage() );
> >> }
> >> }
>
> Pitch wrote:
> > I don't get this. If you are just trying to log all causes, why not use
> > logger?
>
> A) this does use a logger,

Well, if you use Logger implemetation form Apache.org, this does exactly
what you code does (but in fewer lines):

log.error(this, null, trow);


> B) the purpose isn't to show logging but chaining.

So you say inheritance is not the way to go? We should look through the
chained-exceptions to find out if we need to handle a general exception
or not? Doesn't that clutter the code with loops and if-statements?


> If you think I was "just trying to log all causes" then you missed the
point.

Well, why don't you explain if you think I misunderstood something? Or
is it that you think your time is too valuable for a simple explanation?


Anyway I think you're completely wrong and I wouldn't suggest to anyone
to use this approach.

Lew

unread,
Nov 30, 2009, 1:49:14 PM11/30/09
to
Lew wrote:
>>>> It could be said that chained exceptions are a better choice.
>
>>>>   /** Throwable chainer.
>>>>    * @param trow Throwable to chain.
>>>>    * @param log Logger with which to log the chain.
>>>>    */
>>>>   public static void chain( Throwable trow, Logger log )
>>>>   {
>>>>     for ( Throwable last = null, thr = trow;
>>>>           thr != null && thr != last;
>>>>           thr = (last = thr).getCause() )
>>>>     {
>>>>       log.debug( thr.getLocalizedMessage() );
>>>>     }
>>>>   }

Pitch wrote:
>>> I don't get this. If you are just trying to log all causes, why not use
>>> logger?

Lew wrote:
>> A) this does use a logger,
>

Pitch wrote:
> Well, if you use Logger implemetation form Apache.org, this does exactly
> what you code does (but in fewer lines):
>
> log.error(this, null, trow);
>

Exactly what I coded? It uses getLocalizedMessage() and does not
display a stack trace? For all logging libraries? Are you quite
sure?

Lew:


>> B) the purpose isn't to show logging but chaining.
>

Pitch wrote:
> So you say inheritance is not the way to go? We should look through the
> chained-exceptions to find out if we need to handle a general exception
> or not? Doesn't that clutter the code with loops and if-statements?
>

I said it was an alternative, and quite a useful one when the
exceptions are not hierarchically related. In general one cannot
ensure that all exceptions are hierarchically related, and when one
wraps and rethrows with a lower-level exception as a cause, chaining
is the only way to go.

Lew:


>> If you think I was "just trying to log all causes" then you missed the point.
>

Pitch wrote:
> Well, why don't you explain if you think I misunderstood something? Or
> is it that you think your time is too valuable for a simple explanation?
>

It was explained in my post to which you originally replied.


I said:
> It could be said that chained exceptions are a better choice.

Clearly from that you can see that my point was about chained
exceptions, no?

Stow your sarcasm; it was you who missed the point, not I who failed
to explain it.

Pitch wrote:
> Anyway I think you're completely wrong and I wouldn't suggest to anyone
> to use this approach.
>

Too bad for the people you're advising, then. Exception chaining is a
very powerful tool and quite usually the only way to get at root
causes, and it's quite standard throughout the Java universe/

--
Lew

alexandre...@yahoo.fr

unread,
Nov 30, 2009, 1:52:03 PM11/30/09
to
On Nov 27, 4:41 pm, Andre Rothe <aro...@phosco.info> wrote:
...

> Are there any best-practice solutions (patterns?) for this problem? I
> would be happy about some links to examples or discussions.

If you're interesting in some controversial reading or discussions...

It should be noted that there are a lot of Real World [TM]
applications powering, well, pretty much the entire
Real World [TM] that are developed in languages that do not
have the SNAFU concept of checked/unchecked exceptions.

The almighty Joshua Bloch has quite a lot to say on checked
exceptions. For a start, "prefer state testing methods to
checked exceptions".

Lots of food for thoughts in that advice and, of course,
that's how things are done in languages that do not have
the concept of checked exceptions.

If you're interested in views that are unlikely to be
found entertaining in this group, a lot of people consider
checked exception to be GOTO programming.

As an example, we're working on a medium sized codebase
(it's not the Eclipse codebase but it's not either dad & mom's
petstore app) here: a client/server app whose client app
is deployed daily on hundreds of new machines.

The client side app is mostly Java (about 1% of native code)...

The number of checked exceptions we defined in our codebase?

Zero.

Once again, if GOTO-style checked exceptions were mandatory
to be able to develop applications, how would people coding
in languages not supporting checked exceptions do their work?

Food for thought I tell you:

Joshua Bloch: "Prefer state testing methods to checked exceptions".

Why do we define zero checked exceptions? Well, simply because
they don't exist at the OOA/OOD level.

We provide OO abstractions and we translate our OOA/OOD to
Java using only (Java) interfaces.

'Checked exceptions' represent nothing at that level.

People using them are cornering themselves in some Javaites
details that shouldn't exist.

Result? Impossible to port and GOTO-like spaghetti codebase.

Btw I've also worked for a company that wrote an automated
solution for porting applications to hundreds of mobile
devices. We translated Java to Objective-C code automatically
and have published apps on the Apple appstore that reached
the top ten where we wrote exactly *zero* line of Objective-C
code. It was all automated translation. Having a clean
OOA/OOD and straightforward OOD -> OOP that do not rely on
"Javaites" helped a lot of course ;)

Now there's something else... You're talking about rollbacks
and it screams famous RDBs.

OO and RDB don't mix well: they're mostly orthogonal concepts.

And CRUD sucks big times. The next thing is CRA ;)

People and companing working as Java/SQL plumbers have cornered
themselves in one field of the computer industry, Ted Newards
make a very good writing on the subject that gained quite a lot
of traction:

"Object-Relational mapping is the Vietnam of our industry"

If you're interested in reading and discussions, that's a good one.

Did I mention that in addition to using zero checked exceptions
we're using an OO DB?

:)

So, using broken APIs that forces you to do GOTO-style programming
because they know knowing about neither good practices, nor OO, sure,
sometimes you're forced to because you can't do otherwise.

But then of course you can ditch such crappy APIs and go use
APIs and framework from people who "saw the light".

The Spring dudes, for example, puke on checked exceptions because
they're, well, a Gosling brainfart...

From the Spring doc:

"Again in keeping with Spring's philosophy, the ...Exception that
"can be thrown by any of the ... interface's methods is unchecked"

*is unchecked*

That's the Spring philosophy. That's the way to do it.

80's GOTO programming should be dead (it ain't but it should be).

Spring's doc also states that: "JTA is a cumbersome API to use
(partly due to its exception model)"

Do like us, stand on the shoulder of giants.

Listen to what Joshua Bloch says, read about Spring, read on OO.

Take everything written in c.l.j.p. with a grain of salt because
most posters here tend to consider every Gosling brain fart to be
the holy gospel :)

P.S: Lew the grammar nazi can go talk to his psychiatrist about
my grammar and spelling mistakes (not native english speaker here)


Lew

unread,
Nov 30, 2009, 1:56:16 PM11/30/09
to
alexandre_pater...@yahoo.fr wrote:
> P.S: Lew the grammar nazi can go talk to his psychiatrist about
> my grammar and spelling mistakes (not native english speaker here)

<http://en.wikipedia.org/wiki/Godwin%27s_law>

Stop being a troll, "Alexandre".

--
Lew

Arved Sandstrom

unread,
Nov 30, 2009, 5:22:44 PM11/30/09
to

Ahh, give him a break, Lew. He's merely exhibiting youthful enthusiasm,
and an attraction to programming fads born of lack of experience. Right
now it's his anti-SQL, anti-checked exceptions, super-pure OOP phase.
Next year he'll be evangelizing something else.

AHS

Lew

unread,
Nov 30, 2009, 5:34:31 PM11/30/09
to
Arved Sandstrom wrote:
> Ahh, give him a break, Lew. He's merely exhibiting youthful enthusiasm,
> and an attraction to programming fads born of lack of experience. Right
> now it's his anti-SQL, anti-checked exceptions, super-pure OOP phase.
> Next year he'll be evangelizing something else.
>

I have no problem with the on-topic part of his rant. He raises
interesting questions.

It is perhaps far more instructive to suss out why a wrong opinion is
wrong than why a correct opinion is correct.

It is curious to see exception handling regarded as "GOTO-like" and
somehow anti-object-oriented (object-anti-oriented?), given that the
only places I've seen exceptions are in object-oriented languages like
C++ and Java, and, of course, the OP's darling, Objective-C.

--
Lew

Martin Gregorie

unread,
Nov 30, 2009, 8:09:22 PM11/30/09
to
On Mon, 30 Nov 2009 14:34:31 -0800, Lew wrote:

> It is curious to see exception handling regarded as "GOTO-like" and
> somehow anti-object-oriented (object-anti-oriented?), given that the
> only places I've seen exceptions are in object-oriented languages like
> C++ and Java, and, of course, the OP's darling, Objective-C.
>

PL/1 used exceptions, wasn't OO and didn't use them on a particularly
GOTO-like way. I thought they were a pain because the trap didn't have to
be closely related to the place(s) there exceptions occurred - they just
had to be in the same block or an outer level something like:

on endfile(infile)
in_ended = '1'b;;

...
...

do until (in_ended)
read file(infile) into(inrec);
....process inrec....
end;

and you needed another, syntactically unrelated, trap to deal with the
exception caused by opening an non-existent file.


--
martin@ | Martin Gregorie
gregorie. | Essex, UK
org |

Arved Sandstrom

unread,
Nov 30, 2009, 8:16:02 PM11/30/09
to

Well, there isn't a single feature of any programming language that
doesn't eventually get criticized. Pundits, or wannabe pundits, seek to
create or cement reputations by looking for new things to criticize. So,
on this note, you get dubious creeds like
http://www.joelonsoftware.com/items/2003/10/13.html. Once someone with a
bit of a following issues a fatwa, you'll always have some characters
like Alexandre who parrot it without any understanding of right or
wrong. In fact, based on some of his wording, I'd practically guarantee
that he read that Spolsky article.

AHS

Joshua Cranmer

unread,
Nov 30, 2009, 9:36:19 PM11/30/09
to
On 11/30/2009 8:16 PM, Arved Sandstrom wrote:
> Well, there isn't a single feature of any programming language that
> doesn't eventually get criticized. Pundits, or wannabe pundits, seek to
> create or cement reputations by looking for new things to criticize. So,
> on this note, you get dubious creeds like
> http://www.joelonsoftware.com/items/2003/10/13.html. Once someone with a
> bit of a following issues a fatwa, you'll always have some characters
> like Alexandre who parrot it without any understanding of right or
> wrong. In fact, based on some of his wording, I'd practically guarantee
> that he read that Spolsky article.

Return values for exception handling? YUCK.

In my view, there are three main ways of handling exceptions:
1. Pass it through to your caller
2. Ignore it
3. Specifically deal with it

Normal exception handling mechanisms tend to prefer #1, return value
mechanisms prefer #2, and checked exceptions prefer #3.

That return value mechanisms tend to promote swallowing errors is the
basis for my disgust.

--
Beware of bugs in the above code; I have only proved it correct, not
tried it. -- Donald E. Knuth

Tom Anderson

unread,
Nov 30, 2009, 5:54:36 PM11/30/09
to

I am particularly tickled by this idea that 'pure OOP' thing - the idea
that exceptions are Bad and Wrong because they're not in the particular
theoretical model he's arbitrarily latched onto. It could have been so
different if he'd read a different book first!

tom

--
packaheomg sogma's

Arne Vajhøj

unread,
Nov 30, 2009, 10:23:31 PM11/30/09
to
Pitch wrote:
> In article <hf0leh$kob$1...@news.albasani.net>, no...@lewscanon.com says...
>> Lew wrote:
>> B) the purpose isn't to show logging but chaining.
>
> So you say inheritance is not the way to go? We should look through the
> chained-exceptions to find out if we need to handle a general exception
> or not? Doesn't that clutter the code with loops and if-statements?

That is what he showed.

>> If you think I was "just trying to log all causes" then you missed the point.
>
> Well, why don't you explain if you think I misunderstood something?

He just did - see above.

> Anyway I think you're completely wrong and I wouldn't suggest to anyone
> to use this approach.

Exception chaining is a very common technique.

Arne

Pitch

unread,
Dec 1, 2009, 5:32:11 AM12/1/09
to
In article <ab85fdb4-c347-4917-81e8-4d9a172b5078
@m11g2000vbo.googlegroups.com>, l...@lewscanon.com says...

>
> Lew wrote:
> >>>> It could be said that chained exceptions are a better choice.
> >
> >>>>   /** Throwable chainer.
> >>>>    * @param trow Throwable to chain.
> >>>>    * @param log Logger with which to log the chain.
> >>>>    */
> >>>>   public static void chain( Throwable trow, Logger log )
> >>>>   {
> >>>>     for ( Throwable last = null, thr = trow;
> >>>>           thr != null && thr != last;
> >>>>           thr = (last = thr).getCause() )
> >>>>     {
> >>>>       log.debug( thr.getLocalizedMessage() );
> >>>>     }
> >>>>   }
>
> Pitch wrote:
> >>> I don't get this. If you are just trying to log all causes, why not use
> >>> logger?
>
> Lew wrote:
> >> A) this does use a logger,
> >
>
> Pitch wrote:
> > Well, if you use Logger implemetation form Apache.org, this does exactly
> > what you code does (but in fewer lines):
> >
> > log.error(this, null, trow);
> >
>
> Exactly what I coded? It uses getLocalizedMessage() and does not
> display a stack trace? For all logging libraries? Are you quite
> sure?


Well, not exactly, but it's pretty much the same thing. Anyway I don't
see the purpose of your method (related to this topic). And if you
wanted to show chaining it's not necessarry since the original poster
already talked about it.

I'm sorry but I say you posted this code just to show how you can write
cool for-loops.

> Lew:
> >> B) the purpose isn't to show logging but chaining.
> >
>
> Pitch wrote:
> > So you say inheritance is not the way to go? We should look through the
> > chained-exceptions to find out if we need to handle a general exception
> > or not? Doesn't that clutter the code with loops and if-statements?
> >
>
> I said it was an alternative, and quite a useful one when the
> exceptions are not hierarchically related. In general one cannot
> ensure that all exceptions are hierarchically related, and when one
> wraps and rethrows with a lower-level exception as a cause, chaining
> is the only way to go.

Ok, you right, but I would add this: if you design is bad, you must use
any helper tools you can get!

And yes, I think this aproach is a product of a badly designed software.
Exception cause should be only referenced as to be able to list it in
the log files, for history/debug purposes, so to say.

According to the Law of Demeter, a class should not access other than
immediate classes.

http://en.wikipedia.org/wiki/Law_of_Demeter


And isn't exception-chinaing just another buzzword for keeping a simple
reference?


I'm gonna skip the rest of our "misunderstandings" conversation.

Arved Sandstrom

unread,
Dec 1, 2009, 6:29:12 AM12/1/09
to
Pitch wrote:
[ SNIP ]

> And yes, I think this aproach is a product of a badly designed software.
> Exception cause should be only referenced as to be able to list it in
> the log files, for history/debug purposes, so to say.

That's the main use of root cause, yes.

> According to the Law of Demeter, a class should not access other than
> immediate classes.
>
> http://en.wikipedia.org/wiki/Law_of_Demeter

When you're unrolling/unwrapping chained exceptions you're not violating
that law at all. Each access is to an immediate friend. To think that
this process violates the LoD is like thinking that traversing a linked
list violates that law.

> And isn't exception-chinaing just another buzzword for keeping a simple
> reference?

I wouldn't call it a buzzword. The core idea is to wrap the original
exception when you rethrow an exception more suitable for a higher
layer, so as not to lose information. Since you can rethrow several
times it's "chaining". If you didn't use the term "chaining" you would
have to invent one, like...ummm...chaining.

AHS

Pitch

unread,
Dec 1, 2009, 7:13:13 AM12/1/09
to
In article <c67Rm.55832$PH1.28617@edtnps82>, dce...@hotmail.com says...

>
> Pitch wrote:
> [ SNIP ]
>
> > And yes, I think this aproach is a product of a badly designed software.
> > Exception cause should be only referenced as to be able to list it in
> > the log files, for history/debug purposes, so to say.
>
> That's the main use of root cause, yes.
>
> > According to the Law of Demeter, a class should not access other than
> > immediate classes.
> >
> > http://en.wikipedia.org/wiki/Law_of_Demeter
>
> When you're unrolling/unwrapping chained exceptions you're not violating
> that law at all. Each access is to an immediate friend. To think that
> this process violates the LoD is like thinking that traversing a linked
> list violates that law.


e2 = e.getCause();
e3 = e2.getCause();
e4 = e3.getCause();

I don't think e3 is a friend of _this_ class, and that's what Lew's for-
loop does. It accesess all strangers-intances just to call
getLocalizesMessage() on them.

More apropriate would be to do have something like this:

e.getAllLocalizedMessages()

which will internally and recursively use cause member.


> > And isn't exception-chinaing just another buzzword for keeping a
simple
> > reference?
>
> I wouldn't call it a buzzword. The core idea is to wrap the original
> exception when you rethrow an exception more suitable for a higher
> layer, so as not to lose information. Since you can rethrow several
> times it's "chaining". If you didn't use the term "chaining" you would
> have to invent one, like...ummm...chaining.

Every article I've found on the topic of chaining exceptions says
nothing else but that there is a nifty way to stash a reference to the
root eception. There is no special usage of that reference. It didn't
even exist before java 1.4, you had to write it on your own!!!

Lew

unread,
Dec 1, 2009, 9:29:43 AM12/1/09
to
Pitch wrote:
> Every article I've found on the topic of chaining exceptions says
> nothing else but that there is a nifty way to stash a reference to the
> root eception. There is no special usage of that reference. It didn't
> even exist before java [sic] 1.4, you had to write it on your own!!!

It must have been considered quite a useful feature to add exception chaining.
You provide evidence here that exception chaining is a good thing.

--
Lew

Pitch

unread,
Dec 1, 2009, 10:36:10 AM12/1/09
to
In article <hf398n$8b2$2...@news.albasani.net>, no...@lewscanon.com says...

The road to hell is paved with good intentions. :)

Lew

unread,
Dec 1, 2009, 12:26:35 PM12/1/09
to
Pitch wrote:
> The road to hell is paved with good intentions. :)
>

Very cogently argued. ;-}

--
Lew

Tom Anderson

unread,
Dec 1, 2009, 3:15:39 PM12/1/09
to
On Tue, 1 Dec 2009, Arved Sandstrom wrote:

> Pundits, or wannabe pundits, seek to create or cement reputations by
> looking for new things to criticize. So, on this note, you get dubious
> creeds like http://www.joelonsoftware.com/items/2003/10/13.html.

If i ever start a programming blog, i will totally call it Dubious Creeds.

Or a band.

tom

--
around here life is an ambulance eternally carting some dumb idea between
two passing-out brains -- R. Beef Kazenzakis

Tom Anderson

unread,
Dec 1, 2009, 3:23:53 PM12/1/09
to

BBC BASIC had ON ERROR. Usually used like:

10 ON ERROR GOTO 2000
...
2000 start of error-handling code

That's a bit like exception handling, but more like signal handling,
really. I have no idea how it was scoped; i think it wasn't, and the last
ON ERROR seen was used as the error handler. I understand other BASICs
have ON ERROR too, although i can't comment on how it works.

Shell script has a vaguely exception-like behaviour if you do "set -e": if
any command or function evaluates to a nonzero status, the script aborts.
If you structure your apps as multiple files, each doing set -e, then you
get a fail-fast behaviour that is like exceptions, with handling being
done using an || construct. I have scripts that do things like:

$(dirname $0)/start-server.sh || {
echo "Failed to start server: exit code $?"
$(dirname $0)/cleanup-server.sh
}

It ain't pretty, but, well, let's just say it ain't pretty.

John B. Matthews

unread,
Dec 1, 2009, 4:57:59 PM12/1/09
to
In article <alpine.DEB.1.10.0...@urchin.earth.li>,
Tom Anderson <tw...@urchin.earth.li> wrote:

> On Tue, 1 Dec 2009, Arved Sandstrom wrote:
>
> > Pundits, or wannabe pundits, seek to create or cement reputations by
> > looking for new things to criticize. So, on this note, you get dubious
> > creeds like http://www.joelonsoftware.com/items/2003/10/13.html.
>
> If i ever start a programming blog, i will totally call it Dubious Creeds.

No, Dubious Screeds!

> Or a band.

<http://en.wikipedia.org/wiki/Creed_(band)>?

--
John B. Matthews
trashgod at gmail dot com
<http://sites.google.com/site/drjohnbmatthews>

Martin Gregorie

unread,
Dec 1, 2009, 6:17:11 PM12/1/09
to
On Tue, 01 Dec 2009 20:23:53 +0000, Tom Anderson wrote:

> That's a bit like exception handling, but more like signal handling,
> really. I have no idea how it was scoped; i think it wasn't, and the
> last ON ERROR seen was used as the error handler. I understand other
> BASICs have ON ERROR too, although i can't comment on how it works.
>

PL/1 uses it pretty much like Java exceptions in that PL/1 exceptions
can't be ignored (unlike some BASICs) and there is nothing like a try
block.

BASIC was a nightmare: the dialects varied so wildly. Some worked as you
described while others let you specify what condition triggers each ON
CONDITION clause.



> Shell script has a vaguely exception-like behaviour if you do "set -e":
> if any command or function evaluates to a nonzero status, the script
> aborts.
>

That ability to ignore errors at will is common to most operating system
macros as well as UNIX shell scripts.

VME/B had a better approach: the panoramic-conditional:

whenever (conditional expression that recognises exceptions)
begin
actions
end;

and these were scoped by the SCL block structure. SCL was the VME/B
command language.

> It ain't pretty, but, well, let's just say it ain't pretty.
>

It does what's needed. Its always a hard problem to write a command
language that works regardless of whether it is typed in line by line or
run from a file.

Pitch

unread,
Dec 2, 2009, 5:06:00 AM12/2/09
to
In article <ba19a983-2527-4cde-ab6a-c83058316ac7
@t18g2000vbj.googlegroups.com>, l...@lewscanon.com says...

>
> Pitch wrote:
> > The road to hell is paved with good intentions. :)
> >
>
> Very cogently argued. ;-}

Arguments are layed out in my previous posts but here they are again:

- exception chaining is nothing more than a reference to the root cause,
thus they have no functional purpose per se, unless we make use of those
references

- using those references brakes the Law of Demeter

Better alternative is to access only immediate exception, and not to
care about the cause.

EOD

Lew

unread,
Dec 2, 2009, 9:25:47 AM12/2/09
to
Pitch wrote:
> - exception chaining is nothing more than a reference to the root cause,
> thus they have no functional purpose per se, unless we make use of those
> references

Not sure what your point is here. No reference anywhere in programming has a
"functional purpose per se, unless we make use of those references". The
program itself doesn't have a "functional purpose per se, unless we make use
of" it. The definition of "functional" is "we make use of it".

You only use exception chaining when you have a need for wrapped causes.

> - using those references brakes [sic] the Law of Demeter

That was already refuted upthread. You are mistaken. The LoD doesn't apply
here because exceptions are "neighbor" classes to the caller; chaining simply
retrieves multiple instances of those neighbor classes.

> Better alternative is to access only immediate exception, and not to
> care about the cause.

That is not always better. There are valid scenarios when higher-level
exception handlers care about the chain of causality, e.g., for logging and
troubleshooting. The real world is a bitch.

--
Lew

Pitch

unread,
Dec 2, 2009, 5:20:13 PM12/2/09
to
In article <hf5tdc$bmg$1...@news.albasani.net>, no...@lewscanon.com says...

>
> Pitch wrote:
> > - exception chaining is nothing more than a reference to the root cause,
> > thus they have no functional purpose per se, unless we make use of those
> > references
>
> Not sure what your point is here. No reference anywhere in programming has a
> "functional purpose per se, unless we make use of those references". The
> program itself doesn't have a "functional purpose per se, unless we make use
> of" it. The definition of "functional" is "we make use of it".


I will set a few examples where this is not so:

For example, take the length property of a string or an array. It is set
internally when the string is created. It is also used for various
calculations internal to String class.

Also, File class. Several properties like length, lastModified,
getParent, isHidden... are set when the object is created.

Also, URL class and itd getUserInfo is set automatically and is used by
several other classes.

Also, class Thread has getPrority, getState that are also used
internally.

You will see that all those properties are set internally and used by
the class or by some other class in the framework. I say they have their
purpose.


But the cause property of an exception is set by the programmer and used
by the programmer so it's a simple helper property. Something like
"Tag" or "Data" in some other languages and framework. It's not
something that will change the behaviour of the class or try-catch block
or enything in the whole JVM.


> You only use exception chaining when you have a need for wrapped
causes.
>
> > - using those references brakes [sic] the Law of Demeter
>
> That was already refuted upthread.

But it was not. Arve made a comment but he was wrong and I explained
why.


> You are mistaken. The LoD doesn't apply
> here because exceptions are "neighbor" classes to the caller; chaining simply
> retrieves multiple instances of those neighbor classes.


So you think PassswordException from user's Password-Service and
SqlException from JDBC are friend classes? :)

Citation from the Wiki page:

"an object should avoid invoking methods of a member object returned by
another method"

Lew

unread,
Dec 2, 2009, 5:56:15 PM12/2/09
to
Lew says...

>> You are mistaken.  The LoD doesn't apply
>> here because exceptions are "neighbor" classes to the caller; chaining simply
>> retrieves multiple instances of those neighbor classes.
>

Pitch wrote:
> So you think PassswordException from user's Password-Service and

> SqlException [sic] from JDBC are friend classes? :)
>

No, I think 'Throwable' is a "friend" type. 'getCause()' doesn't
return 'PasswordException' or 'SQLException'.

> Citation from the Wiki page:
>
> "an object should avoid invoking methods of a member object returned by
> another method"
>

Since 'Throwable' is a friend, it's always OK to call methods on a
'Throwable'.

You've missed the point of LoD. Since the caller knows about
'Throwable' and that it has a 'getCause()' method, it is not reaching
into the member object's implementation to call 'getCause()' again,
therefore it is not violating LoD. It is using only the knowledge it
has of 'Throwable' to call 'getCause()' in a chain.

Anyway, 'getCause()' is far too useful to let foolish dogma restrict
one's use of it.

--
Lew

Lew

unread,
Dec 2, 2009, 9:26:02 PM12/2/09
to
> In article <hf5tdc$bmg$1...@news.albasani.net>, no...@lewscanon.com says...
>> Pitch wrote:
>>> - exception chaining is nothing more than a reference to the root cause,
>>> thus they have no functional purpose per se, unless we make use of those
>>> references

Lew wrote:
>> Not sure what your point is here. No reference anywhere in programming has a
>> "functional purpose per se, unless we make use of those references". The
>> program itself doesn't have a "functional purpose per se, unless we make use
>> of" it. The definition of "functional" is "we make use of it".

Pitch wrote:
> I will set a few examples where this is not so:
>
> For example, take the length property of a string or an array. It is set
> internally when the string is created. It is also used for various
> calculations internal to String class.

But we do make use of that property. That's why it's exposed to the
programmer. This does not refute the notion that "functional per se" is
equivalent to "we make use of it".

> Also, File class. Several properties like length, lastModified,
> getParent, isHidden... are set when the object is created.

I still don't see what you mean. These properties have a functional purpose,
and we make use of them.

> Also, URL class and itd getUserInfo is set automatically and is used by
> several other classes.

Again, have a "functional purpose per se" and "we make use of them".

> Also, class Thread has getPrority, getState that are also used
> internally.

Ditto.

> You will see that all those properties are set internally and used by
> the class or by some other class in the framework. I say they have their
> purpose.

This does not refute the notion that "functional" and "useful" are equivalent.

> But the cause property of an exception is set by the programmer and used
> by the programmer so it's a simple helper property. Something like

That makes it not functional, or somehow implies that we don't make use of it?

> "Tag" or "Data" in some other languages and framework. It's not
> something that will change the behaviour of the class or try-catch block
> or enything in the whole JVM.

But it is something useful for a programmer.

By your reasoning, we should never use any property that has a 'setX()' method.

--
Lew

Arne Vajhøj

unread,
Dec 2, 2009, 10:01:17 PM12/2/09
to
Pitch wrote:
> In article <ba19a983-2527-4cde-ab6a-c83058316ac7
> @t18g2000vbj.googlegroups.com>, l...@lewscanon.com says...
>> Pitch wrote:
>>> The road to hell is paved with good intentions. :)
>>>
>> Very cogently argued. ;-}
>
> Arguments are layed out in my previous posts but here they are again:
>
> - exception chaining is nothing more than a reference to the root cause,
> thus they have no functional purpose per se, unless we make use of those
> references

Data carrying classes are very common.

> - using those references brakes the Law of Demeter

Yes.

But that seems to indicate a problem with the general validity of that
not a problem with the code.

> Better alternative is to access only immediate exception, and not to
> care about the cause.

Far worse alternative.

Better to violate some obscure rule than to not be able to
trouble shoot an application, because the necessary information
is not available.

Arne

Pitch

unread,
Dec 3, 2009, 5:37:19 AM12/3/09
to
In article <4bf05c3b-5582-4447-b7b9-
cbf0a9...@h2g2000vbd.googlegroups.com>, l...@lewscanon.com says...

>
> Lew says...
> >> You are mistaken.  The LoD doesn't apply
> >> here because exceptions are "neighbor" classes to the caller; chaining simply
> >> retrieves multiple instances of those neighbor classes.
> >
>
> Pitch wrote:
> > So you think PassswordException from user's Password-Service and
> > SqlException [sic] from JDBC are friend classes? :)
> >
>
> No, I think 'Throwable' is a "friend" type. 'getCause()' doesn't
> return 'PasswordException' or 'SQLException'.

LoD does not talk about type hierarchy, but of accessing instances.

>
> > Citation from the Wiki page:
> >
> > "an object should avoid invoking methods of a member object returned by
> > another method"
> >
>
> Since 'Throwable' is a friend, it's always OK to call methods on a
> 'Throwable'.
>
> You've missed the point of LoD. Since the caller knows about
> 'Throwable' and that it has a 'getCause()' method,

I'm sorry but you misssed the point.

By your understanding any type can be a friend if you import it.
Remember, we are talking about e.g. Logger class accessing Throwable.

Anyway it's about instances and methods, not about types.


> Anyway, 'getCause()' is far too useful to let foolish dogma restrict
> one's use of it.

So you declare LoD a foolish dogma. Ok. I'm not saying it's practical to
write such code, but it's a guideline.

Pitch

unread,
Dec 3, 2009, 5:54:20 AM12/3/09
to
In article <hf77jr$hvd$1...@news.albasani.net>, no...@lewscanon.com says...

> > But the cause property of an exception is set by the programmer and
used
> > by the programmer so it's a simple helper property. Something like
>
> That makes it not functional, or somehow implies that we don't make use of it?
>
> > "Tag" or "Data" in some other languages and framework. It's not
> > something that will change the behaviour of the class or try-catch block
> > or enything in the whole JVM.
>
> But it is something useful for a programmer.

> By your reasoning, we should never use any property that has a 'setX
()' method.

Only if it's modifying the behaviour of an object. I even belive that
Sun had been preparing something usefull for the getCause, maybe even it
would be made protected. :)

It would be better that getCause didn't exist at all, and that several
methods were introduced to access full chain of messages and stack-
traces.

Pitch

unread,
Dec 3, 2009, 6:07:40 AM12/3/09
to
In article <4b1729f4$0$269$1472...@news.sunsite.dk>, ar...@vajhoej.dk
says...

> > - exception chaining is nothing more than a reference to the root
cause,
> > thus they have no functional purpose per se, unless we make use of those
> > references
>
> Data carrying classes are very common.

Yes, but they are used in some kind of framework, or in combination with
some other class. So the programmer sets these values so it can use the
object as input to another class.


> > Better alternative is to access only immediate exception, and not to
> > care about the cause.
>
> Far worse alternative.
>
> Better to violate some obscure rule than to not be able to
> trouble shoot an application, because the necessary information
> is not available.

I already indicated how both points could be achieved.

Lew

unread,
Dec 3, 2009, 2:47:19 PM12/3/09
to
Lew wrote:
>> No, I think 'Throwable' is a "friend" type.  'getCause()' doesn't
>> return 'PasswordException' or 'SQLException'.
>

Pitch wrote:
> LoD does not talk about type hierarchy, but of accessing instances.
>

Arved Sandstrom already pointed out:


> When you're unrolling/unwrapping chained exceptions you're not violating
> that law at all. Each access is to an immediate friend. To think that
> this process violates the LoD is like thinking that traversing a linked
> list violates that law.
>

Pitch, you have completely misconstrued LoD to form a dogma that
interferes with effective programming.

--
Lew

Pitch

unread,
Dec 4, 2009, 5:26:43 AM12/4/09
to
In article <9581a260-6546-49f3-80d1-e0417ee40da7
@o13g2000vbl.googlegroups.com>, l...@lewscanon.com says...

Yes, it's less effective but in the long run it's more effective since
you have less errors and better design.

jeremy

unread,
Dec 6, 2009, 9:30:33 AM12/6/09
to

> These are my general rules:

> - layer X catches everything but RuntimeExceptions and throws
> "X_Exception"

> - layer Y catches everything but RuntimeExceptions and throws
> "Y_Exception"

> - GUI/presentation/interface layer catches everything and logs it or
> displays a dialog or whatever.

This is pretty much the Right Way To Do It.

But note that in this case, you have to be careful about using
IllegalArgumentException, as it's a RuntimeException. If code in a
deep
layer is doing input validation (say, taking a user-entered string and
looking something up in a database with it), then failure of
validation
needs to be signalled with a checked layer-specific exception,
otherwise
it will go through the upper layers and annoy the user.

On the other hand, if validation fails for a reason which could have
been
caught by an upper layer (a parameter is null, an argument is too long
or
the wrong colour, etc), then that's a programming error on the part of
the
upper layer, and it's okay to throw an IllegalArgumentException.
Although
it might still be wise to throw a checked exception.

Signature:
[B]steve[/B], [B]cs[/B]
[U]steve[/U], [U]cs[/U]
[I]steve[/I], [I]cs[/I]

0 new messages