Solved

Should I ever throw an exception in asp.net?

Posted on 2009-04-02
8
368 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
8 Comments
 
LVL 9

Assisted Solution

by:Gorkem Yuksel
Gorkem Yuksel earned 50 total points
ID: 24053323
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
ID: 24053464
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
ID: 24054263
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
Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

 
LVL 12

Assisted Solution

by:williamcampbell
williamcampbell earned 50 total points
ID: 24054579
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
 
LVL 3

Assisted Solution

by:OneMHz
OneMHz earned 50 total points
ID: 24055020
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
ID: 24055276
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
ID: 24055541
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
ID: 24055869
@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

Instantly Create Instructional Tutorials

Contextual Guidance at the moment of need helps your employees adopt to new software or processes instantly. Boost knowledge retention and employee engagement step-by-step with one easy solution.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
If you’ve ever visited a web page and noticed a cool font that you really liked the look of, but couldn’t figure out which font it was so that you could use it for your own work, then this video is for you! In this Micro Tutorial, you'll learn yo…
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…

626 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