views:

609

answers:

13

Hi,

nothing more frustrating than to see your code crash in the debugger on a method which exceptionned and you didn't try/catch it.

Is there an easy way to scan through your sources and tag all functions which can potentially throw exceptions?

Does the build in visual assist have some hidden option to colour these functions in a specific color?

thanks

R

+6  A: 

All code but the most trivial could throw exceptions (out of memory, at the very least). You're probably better off writing your code defensively, with at least a global try/catch rather than trying to micromanage which sections of code will or won't throw exceptions.

Clyde
Going along these lines, peer review the code. Even an innocous line such as Int32 x = x / y; could throw a DivideByZero exception. Best practice is to validate all inputs to a method to verify they are within acceptable ranges; which code analysis usually tells you about.
Chris Lively
You guys are saying I should put a try/catch around every line of code, and then deal with all possible things which might happen. This would give one ugly blob of code.Let's just assume that disastrous things like memory exceptions don't occur (in that case your better of logging the event and let it die), I just while I'm coding want to know which methods can potentially give a (documented) exception. A good example of this is Int32.Parse(string). It would be nice if vis studio somehow says: look out, can potentially throw: Null exception or formatexception. And i can deal with it
Toad
+1  A: 

I think the resharper gives you hints on exceptions. But due to the reason that C# doesn't support checked exceptions, there is way to determine the exceptions. Maybe code analysis tools like NDepend support this.

crauscher
thanks for the hint..I'll check them out
Toad
+1  A: 

Everything can throw an exception. Check MSDN for a list of exceptions that can be thrown by a method.

Gerrie Schenck
yes... checking the msdn for every function used is tedious...hence my question ;^)
Toad
+5  A: 

No, there is no way to automatically do this nor is there a good way to get a list of all possible exceptions thrown by a method. Here are a few reasons why

  1. Consider implicitly thrown exceptions such as StackOverflowException can be thrown at any time from any method. You must assume that any method in the CLR can throw these types of exceptions
  2. Reflection and / or delegates can hide the actual code being called in a particular method so you cannot inspect all possible code paths of a method.
  3. This would require inspecting IL vs. metadata.
  4. In .Net there is no requirement to document exceptions that are explicitly thrown by an API
JaredPar
1) These you don't want to handle on a line per line basis... these kinds of exceptions you log globally and restart your program (depending on the app)2) I'm just refering to .Net library calls with the exceptions listed in the help files3) or just a tool with all library calls and their exceptions4) I'm only referring to .Net library calls. This would already be great.
Toad
+1  A: 

All non-empty methods can throw exceptions in one form or another. If you're concerned about exceptions you have personally generated, you can display them from intellisense in the same way framework methods do via XML documentation, like this:

/// <summary>  
/// I seem to have written a method to do a thing.
/// </summary>  
/// <exception cref="System.Exception">An unfortunate failure.</exception>
public void DoSomething()
{
   /* ... */
}
mquander
Intellisense doesnt show any exceptions right now... how do i enable this for .Net library calls?
Toad
+3  A: 

I think redgate have some a tool for this "Exception Hunter" They charge for it after a trial.

http://www.red-gate.com/products/Exception_Hunter/index.htm

76mel
thanks for the tip...I'll check it out
Toad
+ 1 for RedGate, but prepare for the sales calls! I think the real value tends to get drowned out in the noise of all the possible exceptions, but still a decent tool.
TheMissingLINQ
A: 

There is a reflector add in Exception Finder which will show what exceptions could be thrown by a method. I haven't used it but saw an example of it at a .Net users group meeting.

Mark
thanks for the tip...I'll check it out
Toad
A: 

There is a tool out there that can do this. You could download the trial and see if you like it. I don't really think it would be that necessary, but if you are working for a company and they'll pay for it you might want to look into it. Like has been said before there are just too many possible exceptions that be raised. Check out Excpetion Hunter

Mark
thanks for the tip...I'll check it out
Toad
A: 

I find it much more frustrating to break inside an outer catch block and dig my way down to the actual point where the exception happend.

Most of the time if an exception was thrown and I didn't expect it I found a bug and it's easier to solve it if it wasn't obfuscated by some doing-nothing exception handling.

EDIT: Since your examples is actually a good one I'm still not convinced that such a tool would help you. There would be so many possible exceptions that literally every line of code could throw that you would have a hard time to find the "interesting" ones.

VVS
I don't want do nothing exception handlers. I just want to be able to glance through the code beforehand and have some tool point me out the most obvious forgotten try catch blocks
Toad
Do you have an actual example where this is helpful?
VVS
The last exception I got was when the http server returned a '400 bad request'. This resulted in an exception in this line:HttpWebResponse response = (HttpWebResponse) request.EndGetResponse(result);When you think about it, it might be obvious, but it would be nice if a tool points out to me that this function can throw potential exceptions (apart from the stackoverflow/out of memory ones).
Toad
+2  A: 

As others have said, I'm not sure if you'll find a foolproof way of doing this in C# since doesn't support checked exceptions.

As a bit of an aside, this reminded me of an interview with Anders Hejlsberg discussing "The trouble with Checked Exceptions". I'm not trying to flame checked exceptions, but suggesting that you read Ander's rationale behind C#'s exception design and the suggested way for handling exceptions: centralized exception handling.

dariom
I'll read this! thanks!
Toad
Check the comment to my main question to see that Anders in this interview actually agrees with me that a tool for pointing out 'forgotten exception handlers' would be very nice. I'll go through the list of suggested tools, and later post the most relevant one.
Toad
+1  A: 

Any code could potentially cause an exception it is your job to try and anticipate this!

There are a number of third party tools that may assist with finding some common errors e.g fxcop and tools such as refactor can make suggestions.

There is some work been done at the moment that can assist you with finding potential exceptions. Take a look into PEX which can help generate tests for your functions: research.microsoft.com/en-us/projects/Pex/ (link seems to be down at time of posting)

Another exciting area is code contracts (coming in .net 4/available as spec#). Code contracts allow you to write statements that specify conditions that must be met. These can be prior to and after your function being called and you can also declare invariants. A condition might be something as simple as value != null. These conditions are then analyzed at compile and runtime to check no code paths violate them.

alexmac
I do want to anticipate this...but it would be nice if Visual Studio would help me a bit. Opening MSDN for every .Net call is tedious to say the least
Toad
A: 

Exception Hunter mentioned by a few people is a good tool to help with this. I do not know whether it has a tie-in with the <exception> XML-Doc comment so that you can enforce documentation of exceptions thrown by code.

jerryjvl
+1  A: 

As the others have said, you should assume that every single line of code can throw an exception, unless you've proven that it cannot. The better question is, "what do you plan to do about that?"

In general, you should not be catching any exceptions at all.

Of course, everything else is an exception to that rule. It makes sense to catch an exception in order to log it (if your environment doesn't do that for you, as ASP.NET does). It makes sense to catch an exception in order to replace it with another exception that provides more detail about the context:

public int GetConfiguredInteger(string name) {
    string s = null;
    try {
        s = GetStringFromConfigFile(name);
    }
    catch (IOException ex) {
        throw new Exception(String.Format(
            "Error in configuration file foo.config when processing {0}", name),
            ex);
    }
    return int.Parse(s);
}

The caller couldn't have known that the IOException was caused by a config file if you hadn't told them. Note also how I ignored all exceptions not related to the file I/O. In particular, note that the int.Parse is not even inside of the try/catch block.

There are a small number of other such exceptions, but the basic idea of catching exceptions is: don't do it unless it would be worse if you didn't.

John Saunders
I do want to handle exceptions since not handling them means my app failing.a good example is to use it when doing a webrequest. When the remote server returns a 'bad request' html error, this is returned to me in an exception. If one doesn't expect this, your program dies. For these cases, a tool (or intellisense color) would be great to point these possible exceptions out.
Toad
No. When the exception happens, your application has already "failed". If your application depends on a successful webrequest, then a failed one means that your application has failed. In this case, if your app is WinForms, you do want to catch the exception in the event handler that eventually called the web request, then log the exception and maybe display a MessageBox. But the application has already failed, and there's nothing you can do about that. Failed == "Can't do what the user asked".
John Saunders
The app does not have to be failed. It depends totally on the application. Suppose I have remote logging, and the webrequest is my way of logging something. If this fails, my whole program doesn't need to shut down/crash nor does it have to report something to the user. However, I do want to find out in advance that this method can throw an exception, so I can gracefully handle it (and decide myself if the app need to die or do something else, or just ignore it and continue).
Toad
_Every_ method can throw an exception, as has been said. Design instead more broadly. For instance, whether or not to let exceptions cross tiers; how to integrate with logging and other diagnostics, etc. Do not focus, as one might have done with Java, on catching every exception.
John Saunders