| Article: |
Best Practices for Exception Handling | |
| Subject: | A few things | |
| Date: | 2003-12-05 08:17:50 | |
| From: | javid | |
|
I like the article in general.
|
||
Showing messages 1 through 2 of 2.
-
Custom exceptions always have information for client code!
2003-12-23 03:00:26 sebastien.couturiaux [View]
-
Exceptions in unit tests
2003-12-09 10:14:00 zipwow [View]
I felt the same way for a while, but also disliked the number of exception classes that were creeping into my API. Worse, it didn't completely solve the problem, as unless *every* throws clause was different, I could still get a false positive.
What I did was adopt this sentiment:
Every throws clause should construct its exception (of whatever type) with a different *message*. This is helpful anyway, since once I get an exception thrown, even if the code (like in production, say) doesn't keep line numbers, I know where it came from.
Then, in the unit test, I wrote code like this:
try {
makeUser("jimbob","easypassword");
fail("user creation should fail for dictionary password");
} catch (UserException e) {
assertTrue("MyException did not mention dictionary password",
e.getMessage().indexof(DICT_PASSWORD_STRING) != -1);
}
I'm not handling internationalization here, but if you are, I think there's an analagous solution, probably having to do with getMessage() vs getLocalizedMessage().
-Zipwow



My opinion is that custom exceptions always have at least one precious piece of information for client code : their type !!!!
Suppose I create an XYZService that can throw XYZException, simply extending RuntimeException without any additional attribute or method. The ture added value of my custom exception is that I will be able in the client code to filter exception handling precisely for exceptions coming from this XYZService.