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?
Related
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.
I have a C# application..I continuously get a null reference exception..I manage to catch this exception and log it..But i doubt if this exception will affect the performance of my application..Please note that i am not trying to avoid the exception instead i need to know if this exception affects the performance of my application if it is continuously fired .
If you're getting a NullReferenceException, you should fix it rather than catching it. You should only ever catch it if it occurs in code in a way that you cannot fix (e.g. a broken third party library). A NullReferenceException always indicates a programming error somewhere.
As for performance - it depends on what you mean by "continuously". Exceptions can be horribly expensive if they're thrown when nothing's really wrong - they're fine when used properly. How many are you seeing per second, for example? Note that when running in a debugger, exceptions are often much more expensive than they would be when a debugger isn't attached.
As ever, when you're worried about performance, you should test the performance, so you can use hard data to make decisions.
It depends where you handle the exceptions and how often they happen. There is a good article on CodeProject regarding exceptions and performance, I suggest you read it.
Yes it affects it depend upon the frequency of it .
For further info please refer Link and it may also help you Link
Exceptions have been designed to alter performances to a minimum when they are not thrown : adding a try/catch block should have very limited impact to your application performances.
Therefore, I'd recommand to add as many try/catch blocks as required to catch any exception IN THE RIGHT LEVEL.
However, throwing and catching an exception may be very expensive. Application has to switch contexts, dispose any element in using blocks... And that's why I agree with #Ramhound : you ought to fix the exception rather than catching it.
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.
Basically, the question is:
Do the Exceptions in C# affect the performance a lot? Is it better to avoid Exceptions rethrow? If i generate an exception in my code, does it affect a performance?
Sorry for the sillines of the question itself
If you're worried about exception performance, you're using them wrong.
But yes, exceptions do affect performance.
Raising an exception is an expensive operation in C# (compared to other operations in C#) but not enough that I would avoid doing it.
I agree with Jared, if your application is significantly slower because of raising and throwing exceptions, I would take a look at your overall strategy. Something can probably be refactored to make exception handling more efficient rather than dismissing the concept of raising exceptions in code.
Microsoft's Design Guidelines for Developing Class Libraries is a very valuable resource. Here is a relevant article:
Exceptions and Performance
I would also recommend the Framework Design Guidelines book from Microsoft Press. It has a lot of the information from the Design Guidelines link, but it is annotated by people with MS, and Anders Hejlsberg, himself. It gives a lot of insight into the "why" and "how" of the way things are.
running code through a try/catch statement does not affect performance at all. The only performance hit comes if an exception is thrown ... because then the runtime has to unwind the stack and gather other information in order to populate the exception object.
What most other folks said, plus:
Don't use exceptions as part of the programming flow. In other words, don't throw an exception for something like, account.withdrawalAmount > account.balance. That is a business case.
The other biggie to look out for regarding performance is swallowing exceptions. It's a slippery slope, and once you start allowing your app to swallow exceptions, you start doing it everywhere. Now you may be allowing your app to throw exceptions that you don't know about because you are swallowing them, your performance suffers and you don't know why.
This is not silly just I've seen it somewhere else also on SO.
The exceptions occur well, when things are really exceptional. Most of the time you re-throw the exception (may after logging) when there are not many chances of recovering from it. So it should not bother you for normal course of execution of program.
Exceptions as its name implies are intended to be exceptional. Hence you can't expect them to have been an important target for optimisation. More often then not they don't perform well since they have other priorites such as gathering detailed info about what went wrong.
Exceptions in .NET do affect performance. This is the reason why they should be used only in exceptional cases.
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.