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
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.
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
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
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.
This would require inspecting IL vs. metadata.
In .Net there is no requirement to document exceptions that are explicitly thrown by an API
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
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.
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.
Everything can throw an exception. Check MSDN for a list of exceptions that can be thrown by a method.
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()
{
/* ... */
}
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.
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.
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.
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
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.
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.
Related
I am looking for a way to modify catch block depending on if it's executed during the unit test run or not. The purpose is basically to detect/setup mock expectations which are swallowed because catch doesn't rethrow.
I am using MSTest.
One obvious thing is using preprocessor but I don't think it works. Especially if to use DEBUG define. There should be an easy way to detect that, shouldn't it? I must have been looking for something wrong because I couldn't find much info on that.
try {...}
catch(Exception)
{
Log(...);
#if DEBUG
throw;
#endif
}
ANSWER: extract the body of the try into another method and test that instead. Provided by Jon and Ritch. See discussion under Jon's answer. Though thanks everyone for the contribution.
How can you test the exception handling if you want to change the exception handling? Testing the altered behaviour doesn't test what would happen if you didn't alter the behaviour.
Hopefully your mocks have other ways of allowing you to validate expectations at the end of the test, so you can avoid the exception being ignored that way - and you should be testing that your Log and Fix really does happen when you want it to. (Testing logging is tedious and rarely worth it, but presumably Fix does something important.) You should also be testing that the exception isn't rethrown, if that's part of the design.
(As a side matter, catching ArgumentException is usually a bad sign to start with. But maybe in this case it's due to a poorly-designed library you have to use.)
EDIT: Just as a thought, if you're going to be able to test Log and Fix, that means you have to be able to check whether or not they were invoked. In cases where you don't expect an exception to be thrown, you should be able to verify that they weren't called. If they were, you've effectively proved that an exception was thrown.
I still stand by what I said in my comment and Jon seems to agree with me: changing your code on-the-fly just for testing kind of beats the purpose of testing.
If you need to "comment out" some exception handling for your tests to be viable, it might be a sign that you are catching exceptions too early in your code.
Maybe you should refactor your code so that it will not be modified for testing and then design further tests up the call stack to verify that exceptions are handled as you expect it.
"#IF DEBUG" should be used with extreme caution. You are telling the tested code to act differently during test, thus rendering the test pretty close to useless.
Catch specific exception types instead. No exceptions should just be caught silently - they must leave some kind of trail. So, either you throw an exception, or you do something that can be detected by outiders - including your test.
My advice would be to identify the different types of exceptions your code will encounter, and make a catch block for each. Remember that you can create your own exception types:
private class MyException: Exception
{
}
This can be used to organize your exeptions in groups that corresponds to the logic of your code.
If your program is not a windows- or a webservice, I would recommend that you do not catch the basic "Exception" type. This is based on the philosophy that if the program meets unexpected behavior, it should be felt loud and clear. In this context, exceptions should NOT be considered unexpected (i.e. when using a database, one should expect occasional connection problems, timeouts, user issues etc.).
I have a lot of classes that have been written in C#.NET, and I need to know what exceptions can be thrown by them. How I can do it in Visual Studio 2005.
You pretty much can't. Firstly, .NET/C# don't have checked-exceptions like Java, and secondly there are a number of general exceptions that could happen for any freaky reason.
On a method-by-method basis, you can decorate methods with the exceptions they raise, but this is not guaranteed to be present, accurate or complete.
In general, though, any unexpected* exception should be treated as terminal; just unwind, cleaning up (using) etc as you go and propagate the exception - or at least log it if the operation isn't critical.
*=I'll leave aside the philosophical discussion of whether an exception should every truly be expected as such...
You have to look at the code, it is the only source for this.
It is possible to specify what exceptions can be thrown in xml comments but it is not mandatory, so often this imformation is missing.
I'm using VS2008 and have ReSharper too.
My question is how can I automate the creation of a try/catch block for which the catch is specifically populated with the possible exception from the try block? (i.e. not just put in an Exception ex)
Background - Trying to help follow the best practice I read of "Don't catch (Exception) more than once per thread. Good code throws exceptions as needed, and handles only the exceptions it knows how to handle."
thanks
To do that I think you would need a tool that recursively walks your code (and the code it calls, and so forth), and figures out which exceptions could possibly be thrown.
Redgate has a tool that does this. However, I think you probably have a fair idea in your code of what possible exceptions it might throw, and the BCL has decent documentation that says what exceptions might possibly be thrown by any given method you call in the BCL, so it's probably not too hard at the local level to figure out what you need to handle and what you don't.
From what I've read, this was one of the major reasons why the C# team chose not to implement checked exceptions similar to Java - they wanted to discourage this kind of exception non-handling.
There is no means of intrinsically automating such an operation in Visual Studio, nor should you try; if you don't know how to handle a particular exception, then don't catch it just because the library might throw it.
In addition, there are all sorts of special-case system exceptions that might be thrown by the framework, like OutOfMemoryException, BadImageFormatException, AppDomainUnloadedException and so on, that aren't directly thrown by the particular method you're invoking but bubble through it from the .NET runtime. If you wanted to catch all possible exceptions then you'd have to catch these as well, but for the most part it would be a fruitless exercise since there's not much you can do when you get a StackOverflowException - and again, you generally shouldn't attempt to.
In conclusion, the best way to write exception handlers for library methods (and any other methods) is to read the documentation on said method, which will tell you what exceptions you can expect it to throw, and then catch only the ones you actually expect and/or know how to handle. Do not catch the generic System.Exception unless you want spectacular crashes and mysterious data corruption late into the production cycle.
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
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.
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
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
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.
This would require inspecting IL vs. metadata.
In .Net there is no requirement to document exceptions that are explicitly thrown by an API
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
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.
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.
Everything can throw an exception. Check MSDN for a list of exceptions that can be thrown by a method.
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()
{
/* ... */
}
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.
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.
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.
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
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.
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.
If I'm writing a class library, and at some point in that library I have code to catch an exception and deal with it, then I don't want anyone using my library to know that it even happened - it should be invisible from the outside world.
However, if they have "Catch Thrown Exceptions" turned on in Visual Studio (as opposed to "Catch User Unhandled Exceptions") then the exception will be visible to them.
Is there any way to avoid this?
No. This is by design: as a developer, I run with "Catch Thrown Exceptions" turned on, so that I can see exceptions thrown in library code (and hopefully avoid them). The situation you're in applies equally to the .NET framework's own libraries too.
The best way would be to avoid throwing the exception in the first place. As a side benefit, you library code will be faster, since throwing an exception has a noticeable impact on performance (and should only be used in 'exceptional' circumstances).
The only way you can pull this off is if you put a [DebuggerHidden] attribute on the method that may throw the exception. Like others have pointed out, better to avoid the exception altogether, but this attribute will accomplish what you want.
You cannot prevent this. Someone can always attach an debuger to the process and monitor what is going on.
You could just remove the exception and provide the error handling yourself, but I would really not recommend that because it is some kind of reinventing the wheel - recreating the exception handling system.
The said applies of course only if the code throwing and the code catching the exception are far apart and quite unreleated. If they are tightly coupled, you should really check if the call can succeed and only call in this case. Always remeber that exception are intended for exceptional cases - not for normal control flow where you could check if the operation can succeed
As Tim Robinson suggests there is no way to control someone viewing exceptions thrown from your library. His answer is good so I won't rehash it.
There are a couple of posts here on SO that you may find helpful when addressing (what sounds like) using exceptions as program flow control:
Catching exceptions as expected program execution flow control?
Why are .Net programmers so afraid of exceptions?