Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Should I ever throw an exception in asp.net?

Posted on 2009-04-02
8
Medium Priority
?
370 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 200 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
Congratulations! You’re Certified – Now What?

Starting a new career can be overwhelming. Becoming certified in your field of expertise is a great start, but where do you go from here?  Here are some tips to help you on your career journey.

 
LVL 12

Assisted Solution

by:williamcampbell
williamcampbell earned 200 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 200 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 1400 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

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

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

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
This course is ideal for IT System Administrators working with VMware vSphere and its associated products in their company infrastructure. This course teaches you how to install and maintain this virtualization technology to store data, prevent vuln…
In this video, Percona Solutions Engineer Barrett Chambers discusses some of the basic syntax differences between MySQL and MongoDB. To learn more check out our webinar on MongoDB administration for MySQL DBA: https://www.percona.com/resources/we…

715 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