How do I recover from an unchecked exception? - c#

Unchecked exceptions are alright if you want to handle every failure the same way, for example by logging it and skipping to the next request, displaying a message to the user and handling the next event, etc. If this is my use case, all I have to do is catch some general exception type at a high level in my system, and handle everything the same way.
But I want to recover from specific problems, and I'm not sure the best way to approach it with unchecked exceptions. Here is a concrete example.
Suppose I have a web application, built using Struts2 and Hibernate. If an exception bubbles up to my "action", I log it, and display a pretty apology to the user. But one of the functions of my web application is creating new user accounts, that require a unique user name. If a user picks a name that already exists, Hibernate throws an org.hibernate.exception.ConstraintViolationException (an unchecked exception) down in the guts of my system. I'd really like to recover from this particular problem by asking the user to choose another user name, rather than giving them the same "we logged your problem but for now you're hosed" message.
Here are a few points to consider:
There a lot of people creating accounts simultaneously. I don't want to lock the whole user table between a "SELECT" to see if the name exists and an "INSERT" if it doesn't. In the case of relational databases, there might be some tricks to work around this, but what I'm really interested in is the general case where pre-checking for an exception won't work because of a fundamental race condition. Same thing could apply to looking for a file on the file system, etc.
Given my CTO's propensity for drive-by management induced by reading technology columns in "Inc.", I need a layer of indirection around the persistence mechanism so that I can throw out Hibernate and use Kodo, or whatever, without changing anything except the lowest layer of persistence code. As a matter of fact, there are several such layers of abstraction in my system. How can I prevent them from leaking in spite of unchecked exceptions?
One of the declaimed weaknesses of checked exceptions is having to "handle" them in every call on the stack—either by declaring that a calling method throws them, or by catching them and handling them. Handling them often means wrapping them in another checked exception of a type appropriate to the level of abstraction. So, for example, in checked-exception land, a file-system–based implementation of my UserRegistry might catch IOException, while a database implementation would catch SQLException, but both would throw a UserNotFoundException that hides the underlying implementation. How do I take advantage of unchecked exceptions, sparing myself of the burden of this wrapping at each layer, without leaking implementation details?

IMO, wrapping exceptions (checked or otherwise) has several benefits that are worth the cost:
1) It encourages you to think about the failure modes for the code you write. Basically, you have to consider the exceptions that the code you call may throw, and in turn you'll consider the exceptions you'll throw for the code that calls yours.
2) It gives you the opportunity to add additional debugging information into the exception chain. For instance, if you have a method that throws an exception on a duplicate username, you might wrap that exception with one that includes additional information about the circumstances of the failure (for example, the IP of the request that provided the dupe username) that wasn't available to the lower-level code. The cookie trail of exceptions may help you debug a complex problem (it certainly has for me).
3) It lets you become implementation-independent from the lower level code. If you're wrapping exceptions and need to swap out Hibernate for some other ORM, you only have to change your Hibernate-handling code. All the other layers of code will still be successfully using the wrapped exceptions and will interpret them in the same way, even though the underlying circumstances have changed. Note that this applies even if Hibernate changes in some way (ex: they switch exceptions in a new version); it's not just for wholesale technology replacement.
4) It encourages you use different classes of exceptions to represent different situations. For example, you may have a DuplicateUsernameException when the user tries to reuse a username, and a DatabaseFailureException when you can't check for dupe usernames due to a broken DB connection. This, in turn, lets you answer your question ("how do I recover?") in flexible and powerful ways. If you get a DuplicateUsernameException, you may decide to suggest a different username to the user. If you get a DatabaseFailureException, you may let it bubble up to the point where it displays a "down for maintenance" page to the user and send off a notification email to you. Once you have custom exceptions, you have customizeable responses -- and that's a good thing.

I like to repackage exceptions between the "tiers" of my application, so for example a DB-specific exception is repackaged inside of another exception which is meaningful in the context of my application (of course, I leave the original exception as a member so I don't clobber the stack trace).
That said, I think that a non-unique user name is not an "exceptional" enough situation to warrant a throw. I'd use a boolean return argument instead. Without knowing much about your architecture, it's hard for me to say anything more specific or applicable.

See Patterns for Generation, Handling and
Management of Errors
From the Split Domain and Technical Errors pattern
A technical error should never cause a
domain error to be generated (never
the twain should meet). When a
technical error must cause business
processing to fail, it should be
wrapped as a SystemError.
Domain errors should always start from a
domain problem and be handled by
domain code.
Domain errors should
pass "seamlessly" through technical
boundaries. It may be that such errors
must be serialized and re-constituted
for this to happen. Proxies and
facades should take responsibility for
doing this.
Technical errors should
be handled in particular points in the
application, such as boundaries (see
Log at Distribution Boundary).
The
amount of context information passed
back with the error will depend on how
useful this will be for subsequent
diagnosis and handling (figuring out
an alternative strategy). You need to
question whether the stack trace from
a remote machine is wholly useful to
the processing of a domain error
(although the code location of the
error and variable values at that time
may be useful)
So, wrap the hibernate exception at the boundary to hibernate with an unchecked domain exception such as a "UniqueUsernameException", and let that bubble up all the way to the handler of it. Make sure to javadoc the thrown exception even though it isn't a checked exception!

Since you're currently using hibernate the easiest thing to do is just check for that exception and wrap it in either a custom exception or in a custom result object you may have setup in your framework. If you want to ditch hibernate later just make sure you wrap this exception in only 1 place, the first place you catch the exception from hibernate, that's the code you'll probably have to change when you make a switch anyway, so if the catch is in one place then the additional overhead is almost zilch.
help?

I agree with Nick. Exception you described is not really "unexpected exception" so you should design you code accordingly taking possible exceptions into account.
Also I would recommend to take a look at documentation of Microsoft Enterprise Library Exception Handling Block it has a nice outline of error handling patterns.

The question is not really related to checked vs. unchecked debate, the same applies to both exception types.
Between the point where the ConstraintViolationException is thrown and the point, where we want to handle the violation by displaying a nice error message is a large number of method calls on the stack that should abort immediately and shouldn't care about the problem. That makes the exception mechanism the right choice as opposed to redesigning the code from exceptions to return values.
In fact, using an unchecked exception instead of a checked exception is a natural fit, since we really want all intermediate methods on the call stack to ignore the exception and not handle it .
If we want to handle the "unique name violation" only by displaying a nice error message (error page) to the user, there's not really a need for a specific DuplicateUsernameException. This will keep the number of exception classes low. Instead, we can create a MessageException that can be reused in many similar scenarios.
As soon as possible we catch the ConstraintViolationException and convert it to a MessageException with a nice message. It's important to convert it soon, when we can be sure, it's really the "unique user name constraint" that was violated and not some other constraint.
Somewhere close to the top level handler, just handle the MessageException in a different way. Instead of "we logged your problem but for now you're hosed" simply display the message contained in the MessageException, no stack trace.
The MessageException can take some additional constructor parameters, such as a detailed explanation of the problem, available next action (cancel, go to a different page), icon (error, warning)...
The code may look like this
// insert the user
try {
hibernateSession.save(user);
} catch (ConstraintViolationException e) {
throw new MessageException("Username " + user.getName() + " already exists. Please choose a different name.");
}
In a totally different place there's a top exception handler
try {
... render the page
} catch (MessageException e) {
... render a nice page with the message
} catch (Exception e) {
... render "we logged your problem but for now you're hosed" message
}

You can catch unchecked exceptions without needing to wrap them. For example, the following is valid Java.
try {
throw new IllegalArgumentException();
} catch (Exception e) {
System.out.println("boom");
}
So in your action/controller you can have a try-catch block around the logic where the Hibernate call is made. Depending on the exception you can render specific error messages.
But I guess in your today it could be Hibernate, and tomorrow SleepLongerDuringWinter framework. In this case you need to pretend to have your own little ORM framework that wraps around the third party framework. This will allow you to wrap any framework specific exceptions into more meaningful and/or checked exceptions that you know how to make better sense of.

#Jan Checked versus unchecked is a central issue here. I question your supposition (#3) that the exception should be ignored in intervening frames. If I do that, I will end up with an implementation-specific dependency in my high-level code. If I replace Hibernate, catch blocks throughout my application will have to be modified. Yet, at the same time, if I catch the exception at a lower level, I'm not receiving much benefit from using an unchecked exception.
Also, the scenario here is that I want to catch a specific logical error and change the flow of the application by re-prompting the user for a different ID. Simply changing the displayed message is not good enough, and the ability to map to different messages based on exception type is built into Servlets already.

#erikson
Just to add food to your thoughts:
Checked versus unchecked is also debated here
The usage of unchecked exceptions is compliant with the fact they are used IMO for exception caused by the caller of the function (and the caller can be several layers above that function, hence the necessity for other frames to ignore the exception)
Regarding your specific issue, you should catch the unchecked exception at high level, and encapsulate it, as said by #Kanook in your own exception, without displaying the callstack (as mentionned by #Jan Soltis )
That being said, if the underlying technology changes, that will indeed have an impact on those catch() already present in your code, and that does not answer your latest scenario.

Related

Ways to handle exception

Other than logging, what constitutes handling an exception? I ask as people say only catch an exception you can handle.
For example, I wrote a tool to interact with Active Directory. I run it on the domain controller. As I have intimate knowledge of AD, an otherwise-exceptional case I can handle (eg I can raise a prompt to ask for another domain name) and go from there. But if there is a problem with the domain on a production server so critical, would this not be exceptional?
So in this case, a problem with the environment should be exceptional (given that is production and AD etc), yet this is something I can handle. I think handling an exception depends on the program audience (agree)?
Anyway, the main question: to deduce if I can "handle" an exception, I need to know what handle entails - other than logging and presenting the user with another choice (in which case I avoid exceptions by using if file exists etc).
For the above case (AD), I structured my code as:
if (adIsAvailable)
// do whatever here
else
raise exception and ask for action
this is then caught in the gui
Any thoughts on the validity of that design?
Great question.
Remember that you can handle only specific types of exceptions and propagate the really critical ones up the stack and into oblivion.
One type of usage of exception handling is interacting with the user, of course, as you said, the best way is to check a precondition that if violated (file does not exist) will throw an exception, rather than performing the actual task and relying on the exception mechanism for notification.
Another usage of exception handling is retry. For example, you are sending a query to a DB and receive a TimeOutException, or another error that indicates that the connection is temporary unavailable. In this case you might want to wait a bit, and try another time. And only if you fail to reach the Db after, say, 3 times- propagate the exception to the upper layers.
Another way of handling an exception is adding data to the exceptionor changing its type.
You might want to catch a TimeOutException but throw a MyApplicationException that contains, for example, the SQL that you tried to execute (the original exception being the inner exception).
Furthermore, you might want to do the opposite- remove data from the exception, such as the stack- trace, this from security reasons (it is not wise to expose the inner workings of the applications to the malicious user)
In your case by the way, you might want to format a user friendly message that clearly states the nature of the problem, instead of presenting the user with a stack trace and an obscure message. This is another example for a transformation that can be done during exception handling.
Not long ago, I had an exception thrown from my app that rose from insufficient space in a table space on a DML operation. The user got a horrible exception with an error code. What I did is add a handler that inspected the exceptions thrown from the invocation of the command, and added special handling for this error code- it now tells the user exactly what the problem is!
You have a few different issues combined, here.
How to handle (and decide when to handle) exceptions that are thrown by underlying code
When to throw exceptions yourself
Whether production code should treat 'exceptional' situations differently from dev. code.
Regarding point (1):
This can be a bit messy and hard to decide - different APIs might use exceptions differently, even inside the same language.
In C#, for instance, I prefer to use int.TryParse() rather than int.Parse() and catching a FormatException if I expect my input to maybe fail parsing, and I want to write code to handle that case.
If I don't want to handle bad input, I will use int.Parse(), and let the exception propagate.
It depends on the situation, alas.
Regarding point (2):
Exceptions basically mean "I give up". They mean something went wrong, but you aren't going to handle it yourself right there.
Regarding point (3):
I think this is almost always a bad idea.
Aside:
I disagree with part of Vitality's answer, where it says:
the best way is to check a precondition that if violated (file does
not exist) will throw an exception, rather than performing the actual
task and relying on the exception mechanism for notification.
If you write code like:
if (file_exists(x))
{ /* do something */ }
else
{ /* whatever */ }
Then you open yourself up to race conditions.
Maybe the file was deleted in between the file_exists() check, so your code will throw an exception anyway.
Or maybe the file got created just after you entered the else section.
In a case like this, I think it is better to do what you are trying to do, and if something goes wrong, deal with the exception.

Exception handling: user defined exception benefits

My exception handling skills are very primary and I am always very confused about the way I should use them, not so much of the how/syntax. I am currently using C# (if there would be different things applicable to it).
My question is that what are the benefits of creating your own Exception class while developing an application? In comparison to throwing a standard Exception class exception. Basically what is a healthy practice of exceptions in your application.
Or if not benefits, then disadvantages?
By creating your own exceptions you can often create a more meaningful message (or more application specific type of message) for the end user, while still wrapping the original message, so as not to lose any useful information.
There is a great book by Bill Wagner that covers some reasoning about when you should or should not create your own exceptions along with some good practices for exception handling in general. Here is a small excerpt:
Your application will throw exceptions -- hopefully not often, but it
will happen. If you don't do anything specifc, your application will
generate the default .NET Framework exceptions whenever something goes
wrong in the methods you call on the core framework. Providing more
detailed information will go a long way to enabling you and your users
to diagnose and possibly correct errors in the field. You create
different exception classes when different corrective actions are
possible and only when different actions are possible. You create
full-featured exception classes by providing all the constructors that
the base exception class supports. You use the InnerException property
to carry along all the error information generated by lower-level
error conditions.
If there is a specific type of problem unique to your application that will call for a unique recovery strategy at a higher level in your application, you should create your own exception type so you can recognize and recover from that sort of problem optimally.
If the error is more of a "the caller did something wrong" variety, use the standard exception classes.
If you think your library is going to be long-lived and valuable, I would err on the side of creating your own exception classes, so that future users of your library can fashion their own recovery strategy.
Sometimes you want to do diffrent things for diffrent types of error, for example if a user inputs bad data it dosent make sence to crash the whole application and email the administrator. It would make sence to do that for a more serious exeption such as a stack overflow. You would then impliment diffrent catches depending on the type of error.
If a method is documented as throwing some particular class of exception in some particular circumstance, it should ensure that there's no way any exception of the class can bubble up through it in other circumstances. In many cases, the most practical way to ensure this may be to create a custom exception class.
Actually, I would regard much of the exception hierarchy as being pretty useless, and would suggest focusing on a fairly small number of exceptions, from which nearly all good exceptions should derive.
CleanFailureException -- The indicated operation could not be performed for some reason, but has not altered any object's state. There is no reason to believe any object's state is corrupt except to the extent implied by the operation's failure. This should be the type of exception thrown by a DoSomething method if a TrySomething method would return False. May in some cases be wrapped in a more severe instruction, if a failed operation leaves one or more objects in partially-altered or inconsistent states.
StateDisturbedException -- The indicated operation could not be completely performed for some reason, but may have been partially performed. The object on which an action was being performed has a state which complies with its own invariants, but may or may not comply with caller's expectations of it. Caller may attempt to use the object only after examining it and making sure it complies with expectations (changing it as needed). Alternatively, this exception should be caught at the point where the target object would no longer exist, and then wrapped in a CleanFailureException.
TargetStateCorruptException -- The indicated operation could not be performed because the particular object being acted upon is corrupt, but there is no particular reason to expect that corruption extends outside the object. This exception should be caught at the point where the target object would no longer exist, and then wrapped and replaced with CleanFailureException.
ParentStateCorruptException -- The indicated operation could not be performed because some object which the target's documentation would regard as a "parent" object is corrupt. Catch at the level where the corrupt parent objects would no longer exist, then wrap in a "CleanFailureException".
SystemOnFireException
While it may be nice to have exception names that indicate the nature of what went wrong, from a catching perspective what matters is whether one can safely catch and resume. Any exception hierarchy should focus on the latter issues, rather than the former. If the goal is to inform people of what went wrong, that should be done in Exception.Message.
The main benefits are to add information, so exceptions are more meaningful and thus allowing to catch exceptions that are specific to your application.
Throwing an exception is actually a more expensive operation than quietly failing, such as returning a bool. This question highlights what I mean:
How much more expensive is an Exception than a return value?
If you're writing something that you anticipate other developers are going to be using in their own project, then sure, an exception could be useful for them to make sure they're using your code right. Otherwise, if you're just using it within your own codebase, I would make sure to quietly fail.
One example where custom exceptions work well is when you are expecting external applications to interface with your project.
For example, if you had a small project that sends out an email it might make sense to throw a custom 'TooFewRecipients' error if you had a hard limit on the minimum number of recipients that must be emailed.
Custom exceptions will in general inherit from System.Exception
Remember that Exceptions should only be used for exceptional cases which your project can't handle in any other way, and they should be understandable enough to aid a 3rd party developer understand the issue. There is more information at MSDN

How to do Exception Handling & Tracing in C#

I am reading some C# books, and got some exercise don't know how to do, or not sure what does the question mean.
Problem:
After working for a company for some time, your skills as a knowledgeable developer are recognized, and you are given the task of “policing” the implementation of exception handling and tracing in the source code (C#) for an enterprise application that is under constant incremental development. The two goals set by the product architect are:
100% of methods in the entire application must have at least a standard exception handler, using try/catch/finally blocks; more complex methods must also have additional exception handling for specific exceptions
All control flow code can optionally write “tracing” information to assist in debugging and instrumentation of the application at run-time in situations where traditional debuggers are not available (eg. on staging and production servers).
(I am not quite understand these criterias, I came from the java world, java has two kind of exception, check and unchecked exception. Developer must handle checked exception, and do logging. about unchecked exception, still do logging maybe, but most of the time we just throw it. however here comes to C#, what should I do?)
Question for Problem:
List rules you would create for the development team to follow, and the ways in which you would enforce rules, to achieve these goals.
How would you go about ensuring that all existing code complies with the rules specified by the product architect; in particular, what considerations would impact your planning for the work to ensure all existing code complies?
As you mentioned Java has checked and unchecked exceptions. For checked exceptions you have to either declare your method throws it, or handle the exception in the method. C# does not have that limitation, your method doesn't have to declare what exception it could possibly throw.
100% of methods in the entire application must have at least a standard exception handler, using try/catch/finally blocks; more complex methods must also have additional exception handling for specific exceptions
This seems like a stupid requirement. If you have no meaningful way to recover from an exception and continue executing normally, you would ideally allow the exception to bubble up the stack unimpeded. That way when you log the exception (right before shutting down gracefully, or not so gracefully) you'll have a full stack-trace of what exactly caused the exception. It is a very common mistake (from the code I've seen) to use pokemon exception handling and logging the exceptions too early (so you know something bad happened but not what piece of code triggered it.
You should also take a look at this list of similar question for a good overview of good exception handling practices.
And for good measure Vexing exceptions.
After you define your application architecture, you should determine how the exceptions generated by your application will be handled. The strategy should be to meet all security, privacy, and performance requirements. The following are general guidelines for an exception handling strategy:
Do not catch exceptions unless some kind of value can be added. In other words, if knowing about the exception is of no use to the user, to you, or to the application, do not catch it.
Do catch exceptions if you want to retry the operation, add relevant information to the exception, hide sensitive information contained in the exception, or display formatted information.
Generally, handle exceptions only at an application boundary (such as the top of a logical layer, tier, the boundary of a service, or at the top of a UI layer). Also, replace exceptions that contain sensitive information with new exceptions that contain information that can be exposed safely outside the current boundary.
Do not propagate sensitive information across trust boundaries. This is a standard security consideration, but it is frequently overlooked when dealing with exception information. Instead, replace exceptions that contain sensitive information with new exceptions that contain information that can be exposed safely outside the current boundary.
Make exceptions as accurate as possible and allow for specific actions to be taken when the exception is raised. Sometimes this may require writing custom exceptions with the required attributes.
Error messages that are displayed to users should be relevant and they should suggest the corrective action to take. In most cases, user-displayed error messages should never contain sensitive information, such as stack traces or server names.

Exception handling using an HttpModule

We're reviewing one of the company's system's exception handling and found a couple of interesting things.
Most of the code blocks (if not all of them) are inside a try/catch block, and inside the catch block a new BaseApplicationException is being thrown - which seems to be coming from the Enterprise Libraries.
I'm in a bit of a trouble here as I don't see the benefits off doing this. (throwing another exception anytime one occurs)
One of the developers who's been using the system for a while said it's because that class's in charge of publishing the exception (sending emails and stuff like that) but he wasn't too sure about it.
After spending some time going through the code I'm quite confident to say, that's all it does is collecting information about the environment and than publishing it.
My question is:
- Is it reasonable to wrap all the code inside try { } catch { } blocks and than throw a new exception? And if it is, why? What's the benefit?
My personal opinion is that it would be much easier to use an HttpModule, sign up for the Error event of the Application event, and do what's necessary inside the module. If we'd go down this road, would we miss something? Any drawbacks?
Your opinion's much appreciated.
Never1 catch (Exception ex). Period2. There is no way you can handle all the different kinds of errors that you may catch.
Never3 catch an Exception-derived type if you can't handle it or provide additional information (to be used by subsequent exception handlers). Displaying an error message is not the same as handling the error.
A couple of reasons for this, from the top of my head:
Catching and rethrowing is expensive
You'll end up losing the stack trace
You'll have a low signal-to-noice ratio in your code
If you know how to handle a specific exception (and reset the application to pre-error state), catch it. (That's why it's called exception handling.)
To handle exceptions that are not caught, listen for the appropriate events. When doing WinForms, you'll need to listen for System.AppDomain.CurrentDomain.UnhandledException, and - if your doing Threading - System.Windows.Forms.Application.ThreadException. For web apps, there are similar mechanisms (System.Web.HttpApplication.Error).
As for wrapping framework exceptions in your application (non-)specific exceptions (i.e. throw new MyBaseException(ex);): Utterly pointless, and a bad smell.4
Edit
1 Never is a very harsh word, especially when it comes to engineering, as #Chris pointed out in the comments. I'll admit to being high on principles when I first wrote this answer.
2,3 See 1.
4 If you don't bring anything new to the table, I still stand by this. If you have caught Exception ex as part of a method that you know could fail in any number of ways, I believe that the current method should reflect that in it's signature. And as you know, exceptions is not part of the method signature.
If I am reading the question correctly, I would say that implementing a try / catch which intercept exceptions (you don't mention - is it catching all exceptions, or just a specific one?) and throws a different exception is generally a bad thing.
Disadvantages:
At the very least you will lose stack trace information - the stack you will see will only extend to the method in which the new exception is thrown - you potentially lose some good debug info here.
If you are catching Exception, you are running the risk of masking critical exceptions, like OutOfMemory or StackOverflow with a less critical exception, and thus leaving the process running, where perhaps it should have been torn down.
Possible Advantages:
In some very specific cases you could take an exception which doesn't have much debug value (like some exceptions coming back from a database) and wrap with an exception which adds more context, e.g id of the object you were dealing with.
However, in almost all cases this is a bad smell and should be used with caution.
Generally you should only catch an exception when there is something realistic that you can do in that location- ie recovering, rolling back, going to plan B etc. If there is nothing you can do about it, just allow it to pass up the chain. You should only catch and throw a new exception if there is specific and useful data available in that location which can augment the original exception and hence aid debugging.
I'm from the school of thought where try/ catch blocks should be used and exceptions not rethrown. If you have executing code which is likely to error then it should be handled, logged and something returned. Rethrowing the exception only serves the purpose to re-log later in the application life cycle.
Here's an interesting post on how to use a HttpModule to handle exceptions: http://blogs.msdn.com/rahulso/archive/2008/07/13/how-to-use-httpmodules-to-troubleshoot-your-asp-net-application.aspx and http://blogs.msdn.com/rahulso/archive/2008/07/18/asp-net-how-to-write-error-messages-into-a-text-file-using-a-simple-httpmodule.aspx
Check out ELMAH. It does what you're talking about. Very well.
When I create libraries I try to always provide a reduced number of exceptions for callers to handle. For example, think of a Repository component that connects to a sql database. There are TONS of exceptions, from sql client exceptions to invalid cast exceptions, that can theoretically be thrown. Many of these are clearly documented and can be accounted for at compile time. So, I catch as many of them as I can, place them in a single exception type, say a RepositoryException, and let that exception roll up the call stack.
The original exception is retained, so the original exception can be diagnosed. But my callers only need to worry about handling a single exception type rather than litter their code with tons of different catch blocks.
There are, of course, some issues with this. Most notably, if the caller can handle some of these exceptions, they have to root around in the RepositoryException and then switch on the type of the inner exception to handle it. Its less clean than having a single catch block for a single exception type. I don't think thats much of an issue, however.
Sounds like the exception that is thrown should not have been implemented as an exception.
Anyway, I would say that since this BaseApplicationException is a general all-purpose exception, it would be good to throw exceptions that are more context-specific. So when you are trying to retrieve an entity from a database, you might want an EntityNotFoundException. This way when you are debugging you do not have to search through inner exceptions and stack traces to find the real issue. If this BAseApplicationException is collecting information on the exception (like keeping track of the inner exception) then this should not be a problem.
I would use the HttpModule only when I could not get any closer to where the exceptions are actually happening in code. You do not really want an HttModule OnError event that is a giant switch statement depending on BaseApplicationexception's error information.
To conclude, it is worth it to throw different exceptions when you can give more specific exceptions that tell you the root of the problem right off the bat.
From my experience, catch the exception, add the error to the Server (?) object. This will allow .NET to do what ever it needs to do, then display your exception.

Do you write exceptions for specific issues or general exceptions?

I have some code that gives a user id to a utility that then send email to that user.
emailUtil.sendEmail(userId, "foo");
public void sendEmail(String userId, String message) throws MailException {
/* ... logic that could throw a MailException */
}
MailException could be thrown for a number of reasons, problems with the email address, problems with the mail template etc.
My question is this: do you create a new Exception type for every one of these exceptions and then deal with them individually or do you create one MailException and then store something in the exception (something computer-readable, not the description text) that allows us to do different things based on what actually happened.
Edit: As a clarification, the exceptions aren't for logs and what-not, this relates to how code reacts to them. To keep going with the mail example, let's say that when we send mail it could fail because you don't have an email address, or it could because you don't have a valid email address, or it could fail.. etc.
My code would want to react differently to each of these issues (mostly by changing the message returned to the client, but actual logic as well).
Would it be best to have an exception implementation for each one of these issues or one umbrella exception that had something internal to it (an enum say) that let the code distinguish what kind of issue it was.
In my code, I find that MOST exceptions percolate up to a UI layer where they are caught by my exception handlers which simply display a message to the user (and write to the log). It's an unexpected exception, after all.
Sometimes, I do want to catch a specific exception (as you seem to want to do). You'll probably find, however, that this is somewhat rare and that it is indicative of using exceptions to control logic -- which is inefficient (slow) and often frowned upon.
So using your example, if you want to run some special logic when the email server is not configured, you may want to add a method to the emailUtil object like:
public bool isEmailConfigured()
... call that first, instead of looking for a specific exception.
When an exception does happen, it really means that the situation was completely unexpected and the code can't handle it -- so the best you can do is report it to the user (or write it to a log or restart )
As for having an exception hierarchy vs exceptions-with-error-codes-in-them, I typically do the latter. It's easier to add new exceptions, if you just need to define a new error constant instead of a whole new class. But, it doesn't matter much as long as you try to be consistent throughout your project.
I usually start with a general exception and subclass it as needed. I always can catch the general exception (and with it all subclassed exceptions) if needed, but also the specific.
An example from the Java-API is IOException, that has subclasses like FileNotFoundException or EOFException (and much more).
This way you get the advantages of both, you don't have throw-clauses like:
throws SpecificException1, SpecificException2, SpecificException3 ...
a general
throws GeneralException
is enough. But if you want to have a special reaction to special circumstances you can always catch the specific exception.
#Chris.Lively
You know you can pass a message in your exception, or even the "status codes". You are reinventing the wheel here.
I have found that if you need to have CODE deciding what to do based on the exception returned, create a well named exception subclassing a common base type. The message passed should be considered "human eyes only" and too fragile to make decisions upon. Let the compiler do the work!
If you need to pass this up to a higher layer through a mechanism not aware of checked exceptions, you can wrap it in a suitable named subclass of RuntimeException (MailDomainException) which can be caught up high, and the original cause acted upon.
It depends on what your application is doing. You might want to throw individual exceptions in cases like
The application is high availability
Sending e-mail is particularly important
The scope of the application is small and sending e-mail is a large part of it
The application will be deployed to a site which is remote and you will only get logs for debugging
You can recover from some subset of the exceptions encapsulated in the mailException but not others
In most cases I would say just log the text of the exception and don't waste your time granularizing already pretty granular exceptions.
I think a combination of the above is going to give you the best result.
You can throw different exceptions depending on the problem. e.g. Missing email address = ArgumentException.
But then in the UI layer you can check the exception type and, if need be, the message and then display a appropriate message to the user. I personally tend to only show a informational message to the user if a certain type of exception is thrown (UserException in my app). Of course you should scrub and verify user input as much as possible further up the stack to make sure any exceptions are generated by truly unlikely scenarios, not as a filter for malformed emails which can easily be checked with a regex.
I also wouldn't worry about the performance implications of catching an exception from user input. The only time you are going to see performance problems from exceptions is when they are being thrown and caught in a loop or similar.
Instead of using exceptions, I tend to return a list of status objects from methods that may have problems executing. The status objects contain a severity enum (information, warning, error, ...) a status object name like "Email Address" and a user readable message like "Badly formatted Email Address"
The calling code would then decide which to filter up to the UI and which to handle itself.
Personally, I think exceptions are strictly for when you can't implement a normal code solution. The performance hit and handling restrictions are just a bit too much for me.
Another reason for using a list of status objects is that identifying multiple errors (such as during validation) is MUCH easier. After all, you can only throw one exception which must be handled before moving on.
Imagine a user submitting an email that had a malformed destination address and contained language that you are blocking. Do you throw the malformed email exception, then, after they fix that and resubmit, throw a bad language exception? From a user experience perspective dealing with all of them at once is a better way to go.
UPDATE: combining answers
#Jonathan: My point was that I can evaluate the action, in this case sending an email, and send back multiple failure reasons. For example, "bad email address", "blank message title", etc..
With an exception, you're limited to just percolating the one problem then asking the user to resubmit at which point they find out about a second problem. This is really bad UI design.
Reinventing the wheel.. possibly. However, most applications should analyze the whole transaction in order to give the best possible information to the user. Imagine if your compiler stopped dead at the first error. You then fix the error and hit compile again only to have it stop again for a different error. What a pain in the butt. To me, that's exactly the problem with throwing exceptions and hence the reason I said to use a different mechanism.
I tend to have less Exception types, although it's not really the OO way to do it. Instead I put an enum to my custom Exceptions, which classifies the Exception. Most of the time I have a custom base Exception, which holds on to a couple of members, which can be overridden or customized in derived Exception types.
A couple of months ago I blogged about the idea of how to internationalize Exceptions. It includes some of the ideas mentioned above.
While you can differenciate the code execution looking the exception don't matter if it's done by the "catch exceptionType hierarchy mode" or by "if(...) else...exception code mode"
but if you are developing software wich is going to be used by other people, like a library i think it's usefull create your own exception types to notice the other people that your sofware can throw other exceptions than the normal ones, and they better catch and resolve them.
When i use a library and their methods simply launch an 'Exception' i allways wonder: What can cause this exception?, how must my program react?, if there is a javadoc maybe the cause will be explained, but mustly of times there is not a javadoc or the exception is not explained. Too much overhead witch can be avoided with a WellChossenExceptionTypeName
It depends on whether the code that catches the exception needs to differentiate between exceptions or whether you are just using exceptions to fail out to an error page. If you need to differentiate between a NullReference exception and your custom MailException higher up in the call stack, then spend the time and write it. But most of the time programmers just use exceptions as a catch all to throw up an error on the web page. In this case you are just wasting effort on writing a new exception.
I would just go by
throw new exception("WhatCausedIt")
if you want to handle your exceptions, you could pass a code instead of "WhatCausedIt" an then react to the different answers with a switch statement.

Categories

Resources