Solved

Should I ever throw an exception in asp.net?

Posted on 2009-04-02
8
363 Views
Last Modified: 2012-05-06
In asp.net 3.5, is it valid to throw an exception for invalid arguments, for example?  I disagree with this since the caller isn't going to do anything special with the exception.  So why throw it?  I say if you aren't going to handle the exception then let your friendly formatted errorpage.aspx report it.  I'd like to hear arguments for against throwing exceptions.  I'm not sure why someone would want to throw an exception just to report a problem.
0
Comment
Question by:brettr
8 Comments
 
LVL 9

Assisted Solution

by:Gorkem Yuksel
Gorkem Yuksel earned 50 total points
Comment Utility
Hi brettr,

Throwing an exception is used for a wide range of reasons.  I use them when I branch out into custom classes that I build.  The class will throw my own custom exceptions when needed to tell my main page that it could not do something, which in turn will need to handle the exception event.

Cheers,

G.
0
 

Author Comment

by:brettr
Comment Utility
Your main page might get a wide range of exceptions.  How does it know which type of exception and what does it do with them?
0
 
LVL 21

Expert Comment

by:Craig Wagner
Comment Utility
I'm not sure I understand the question. You ask about throwing exceptions, but then you talk about your errorpage.aspx handling it.

Throwing exceptions are the correct way to report unrecoverable situations. If your page expects to receive a parameter and it doesn't, throwing an exception gets out out of the page. If you've got a standard error-handling page the user will end up there. The error-handling page should log the exception so that a maintenance programming or operations person can see that something went wrong, what it was, and where it happened, and the end user sees a nice standard error.
0
 
LVL 12

Assisted Solution

by:williamcampbell
williamcampbell earned 50 total points
Comment Utility
The general rule is only throw an exception when a resource is missing, a file,image.database etc  if something really bad happened report an error (Alert)   throwing random exceptions into the verse usually ends up with a nasty looking stack trace ... and a miffed user
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 3

Assisted Solution

by:OneMHz
OneMHz earned 50 total points
Comment Utility
You should throw exceptions when something unexpected that you can't handle otherwise happens (missing or null function parameters that are needed to call a stored procedure is a perfect example).  But, the calling code (aka your UI layer) should handle these exceptions to avoid showing the stack trace (a message to the user to enter the needed info).  If you can handle an error and return a reasonable result or an error message to display, then don't throw an exception.  Exceptions shouldn't be used in place of say an if block.
0
 

Author Comment

by:brettr
Comment Utility
I agree with williamcampbell and completely disagree with CraigWagner.  It's sloppy to throw exceptions for anything and everything.

@williamcampbell and OneMHz:

How should some sort of message/alert get to the UI from way down where the exception occurred and was handled?  You swallowed the exception but the UI should still know what's going on.

If you are doing checks on arguments coming into your method and get an invalid argument in the check, should you throw an exception?  Probably not.  You're compensating for this bad argument by checking for it.  But of course, you can't go on.  If your method is a void, what should you do for getting control back into the program and out of your bad but recoverable situation?
0
 
LVL 21

Accepted Solution

by:
Craig Wagner earned 350 total points
Comment Utility
Your original question was pretty vague, and as a result my answer was somewhat vague. The point is, if your method cannot continue due to some condition, throw an exception. Exceptions are not for the benefit of the user, they should never see the exception (which is why I don't understand williamcampbell's comment about a miffed user, they should never know an exception occurred). Exceptions are for the benefit of the poor maintenance programmer who has to fix the problem (because getting into a situation where an exception is thrown often indicates a bug in the system) so they can find out where in the code the condition occurred and how you got there.

"How should some sort of message/alert get to the UI from way down where the exception occurred and was handled?  You swallowed the exception but the UI should still know what's going on."

The way the alert gets to the UI is by either rethrowing the exception or letting it bubble up. That's what the exception is for, to communicate an inability to continue that cannot be ignored as you go up the call stack. Good exception handling practice says you only catch the exception where you can do something about it. Often (usually) doing something about it means logging it and gracefully exiting whatever you were doing at the time. In the case of a web application, the latter usually means transferring the user to a generic error page. So if I've got some code that throws a DivideByZeroException, I let that bubble all the way to the top of the call stack (typically the UI, unless we're talking about a Web Service or Windows Service) where I catch the exception, log it, and present the user with a 'friendly' message.

"If you are doing checks on arguments coming into your method and get an invalid argument in the check, should you throw an exception?"

Can the argument be ignored if it is outside of the acceptable range? Can you plug in a default value? If there is no way to recover from the bad argument, you should absolutely throw an exception. Why do you think System.ArgumentException, System.ArgumentNullException, and System.ArgumentOutOfRangeException exist?

"You're compensating for this bad argument by checking for it.  But of course, you can't go on.  If your method is a void, what should you do for getting control back into the program and out of your bad but recoverable situation?"

It's not a recoverable situation. The method got a bad argument. It cannot continue. Throw an exception to get out and communicate up the call stack that "something bad happened." If the bad value is due to bad user input, that indicates a bug in your UI layer (you're not validating the input before blithely passing the data down into the guts of your application). Add UI-level validation.

Look at how the .NET framework works. If I try to delete a file that is marked read-only (using File.Delete) I get an exception, not a status code or some other method of failure notification.

I should point out that I'm not just pulling these ideas out of my butt. They are based on documented best practices (see below) and I've used them to create robust, easy-to-maintain applications and architectures at four different companies over the past ten years.

This quote is from the following article: "Exceptions offer several advantages over other methods of error notification, such as return codes. Failures do not go unnoticed. Invalid values do not continue to propagate through the system. You do not have to check return codes. Exception-handling code can be easily added to increase program reliability."

http://msdn.microsoft.com/en-us/library/5b2yeyab.aspx

http://www.codeproject.com/KB/architecture/exceptionbestpractices.aspx
0
 

Author Comment

by:brettr
Comment Utility
@CraigWagner
Good explanations.

>>So if I've got some code that throws a DivideByZeroException, I let that bubble all the way to the top of the call stack...and present the user with a 'friendly' message.<<

Why let the exception continue?

>>Can the argument be ignored if it is outside of the acceptable range? Can you plug in a default value? If there is no way to recover from the bad argument, you should absolutely throw an exception.<<

I agree with the first two questions but why throw?  An exception occurred so let it continue bubbling up.  Your errorpage will catch it and display something friendly.

Thanks on the links.
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

7 Experts available now in Live!

Get 1:1 Help Now