I have some framework / AOP code that logs exceptions from methods called deeper inside...
try {
..invoke inner code...
}
catch (Exception e) {
log(e);
throw;
}
This works great except for one thing...when my team tries to debug their code in Studio, they only see the exception happening in the logging code (since it gets handled, and then thrown from there).
Is there any way I can get Studio to ignore that my code is catching/throwing an exception...or to inspect the exception on it's way through without catching it?
UPDATE:
The issue is that I have framework code that prevents the correct break-point for the real exception from being hit. I am aware that the debugger in visual studio is capable of fine-grained configuration, and I am hoping that someone here can provide a higher level insight than "Learn VS2010 in 31 Hours" does. I simply want to BOTH log the exceptions that are caused in inner code, AND have the break happen at the site of the error WITHOUT turning on 'Break on All Exceptions' which would cause my team to spend 5 minutes pressing the 'Continue' button every time they launched the app (but that's another story).
UPDATE 2:
The primary question here, is how can I log the exception, but have the debugger not stop on the 'throw' in my logger, but on the initial exception, without having the debugger stop on all exceptions thrown.
Actually you can make VS break on exceptions. Go to the Debug menu, click exceptions and check both the checkboxes for "Common Language Runtime Exceptions". Now you'll get a debug break at the point the exception is thrown.
I've done some digging, and the answer in 1349613 put me on a good scent. I've added the attribute:
[DebuggerNonUserCode]
To my logging class. Now when the internal, invoked code throws an exception, the debugger ignores the logging code, and it's Try/Catch block, and goes straight to the internal exception.
It is possible in VB.NET to examine an exception without catching it, and before any stack unwinding has occurred as a consequence of it. While it is generally dangerous to do very much between the time the exception has been thrown and the time the stack has been unwound, one may capture the exception and then make use of it in a finally block. One might also set a flag or other indicator to let stack-unwinding code know where the exception is going to be caught. Unfortunately, the usefulness of the latter ability is limited because of a (largely language-forced) anti-pattern of code catching exceptions that it needs to react to, but that can't expect to resolve. For example, if an exception is thrown in a constructor after it has created some IDisposable objects and stored them in fields, the constructor has to react to the exception by cleaning up the fields it has created, but has no hope of resolving the situation and returning normally. If a constructor might have multiple return points, it would be semantically cleaner of one could say:
try
{
... create IDisposables
}
finally(Exception ex)
{
if (ex != null)
this.Dispose();
}
than having to say
try
{
... create IDisposables
}
catch(Exception ex)
{
this.Dispose();
throw ex;
}
since the former would avoid catching an exception it had no expectation of handling. One could write a wrapper method in VB that would accept a pair of delegates and implement the second using the same semantics as the finally(Exception ex) above would have, but unfortunately C# provides no such facility itself.
Related
I have a large C# code base. It seems quite buggy at times, and I was wondering if there is a quick way to improve finding and diagnosing issues that are occuring on client PCs.
The most pressing issue is that exceptions occur in the software, are caught, and even reported through to me. The problem is that by the time they are caught the original cause of the exception is lost.
I.e. If an exception was caught in a specific method, but that method calls 20 other methods, and those methods each call 20 other methods. You get the picture, a null reference exception is impossible to figure out, especially if it occured on a client machine.
I have currently found some places where I think errors are more likely to occur and wrapped these directly in their own try catch blocks. Is that the only solution? I could be here a long time.
I don't care that the exception will bring down the current process (it is just a thread anyway - not the main application), but I care that the exceptions come back and don't help with troubleshooting.
Any ideas?
I am well aware that I am probably asking a question which sounds silly, and may not have a straightforward answer. All the same some discussion would be good.
Exceptions maintain the call stack which you can use to trace the source of the exception unless the exception is rethrown improperly or is swallowed. By the former, I mean something like:
try
{
//...
}
catch ( Exception e )
{
//do stuff with exception
throw e;
}
Instead of :
try
{
//...
}
catch ( Exception )
{
//do stuff with exception
throw;
}
The later maintains the call stack whereas the former does not. In general, code should only catch exceptions that it plans on handling rather than all exceptions. If the code is properly designed this way, then when the top most layer catches the exception, you should have via the call stack the method that started the chain of events.
When an unexpected exception occurs in your program (in the debugger). Sometimes you just want to skip it since killing the program at that point is more harmful than continuing. Or you just want to continue since you were more interested in another error/bug
Is there an option/compilerflag/secretswitch to enable this?
I understand exceptions should be resolved right away, but there are scenarios (like I described) where one just wants to skip it for the time-being
You can't do this without an appropriate catch block in your code, no. However, I can't remember ever wanting to do this: if an exception occurs which your code doesn't know how to genuinely handle, why would you want to continue? You're in a bad state at that point - continuing would be dangerous.
Can you give an example of why you'd want to continue in a debugger session but not in production code?
Exceptions in C# are not resumable, but events are - and that is how resumable exceptions are typically implemented: as cancellable events. See also this question.
Use a try-catch block, and when catching, don't do anything about the exception.
If you are into the debugger then right click on the line you want to continue and select: Set Next Statement... but use it at your own risk!
When stepping through the code in debug mode you could skip the execution of the instructions that throw the undesired exception. But if the exception is already thrown and you don't have a try/catch it will propagate.
Have a look at the Exception Handling Application Block and related documentation. It contains best practices for handling application exceptions and there is a lot of framework code done for you i.e. logging.
If you want to know what exception you want to allow. then you can do this below
try
{
// your functionality
}
catch(Exception ex)
{
// Catch only the exceptions you need to point out
}
finally
{
//do what you want to complete with this function.
}
I assume that by "skipping" you mean that you want your program to continue working after the exception.
That, of course, is possible by catching the exception when using try-catch block.
If the exception is not application stopper (for example, some key variable is not initialized after the exception, and you can't continue work) it is recommended that you at least log it before continue. Of course, putting
catch (Exception e) { }
everywhere in your source will not lead to a stable application ;)
If your problem is more debugger-related (you don't want the debugger to stop on every thrown exception), then there is a place in VS where you can change this:
In the Debug menu, select Exceptions. You'll see all possible exceptions and you can adjust their behaviour when thrown or not handled by the user.
I’m used to having try/catch blocks in every method. The reason for this is so that I can catch every exception at the point of infraction and log it. I understand, from my reading and conversations with others, that this isn’t a popular view. One should only catch what one is prepared to handle. However, if I don’t catch at the point of infraction, then it would be possible to never log that infraction and know about it. Note: When I do catch and don’t handle, I still throw. This allows me to let the exception propagate to something that will handle it, yet still let me log it at the point of infraction.
So... How does one avoid try/catch in every method, yet still log the error at the point at which it occurred?
No, don't catch everything. Exceptions propagate higher up on the stack. All you have to do is make sure that the exception is caught before it gets to the top of the stack.
This means, for instance, that you should surround the code of an event handler with a try/catch block. An event handler may be the "top of the stack". Same for a ThreadStart handler or a callback from an asynchronous method.
You also want to catch exceptions on layer boundaries, though in that case, you might just want to wrap the exception in a layer-specific exception.
In the case of ASP.NET, you may decide to allow ASP.NET Health Monitoring to log the exception for you.
But you certainly don't ever need to catch exceptions in every method. That's a major anti-pattern. I would loudly object to you checking in code with that kind of exception handling.
You can see everything at stack trace - no need to try/catch every method.
Stick to few rules:
Use try/catch only if you want to use a custom exception type
Define a new exception type only if upper levels needs to know that
Try/catch at top level instead of doing that for each method
OK, having read all the answers saying you should have a single try/catch at the top level, I'm going to weigh in with an alternative view.
I wouldn't put a try/catch in every method, far from it. But I would use a try/catch around sections of code that I expected to fail (e.g. opening a file), and where I wanted to add additional information to the exception (to be logged higher up the chain).
A stack trace saying and a message saying "permission denied" might be enough to allow you as a programmer to figure out what went wrong, but my goal is to provide the user with meaningful information, such as "Could not open file 'C:\lockedfile.txt'. Permission denied.".
As in:
private void DoSomethingWithFile(string filename)
{
// Note: try/catch doesn't need to surround the whole method...
if (File.Exists(filename))
{
try
{
// do something involving the file
}
catch (Exception ex)
{
throw new ApplicationException(string.Format("Cannot do something with file '{0}'.", filename), ex);
}
}
}
I'd also like to mention that even the people saying "only have one try/catch" would presumably still use try/finally throughout their code, since that's the only way to guarantee proper cleanup, etc.
Catching and rethrowing an exception that you cannot handle is nothing more than a waste of processor time. If you can't do anything with or about the exception, ignore it and let the caller respond to it.
If you want to log every exception, a global exception handler will do just fine. In .NET, the stack trace is an object; its properties can be inspected like any other. You can write the properties of the stack trace (even in string form) to your log of choice.
If you want to ensure that every exception is caught, a global exception handler should do the trick. In point of fact, no application should be without one.
Your catch blocks should only catch exceptions that you know that you can gracefully recover from. That is, if you can do something about it, catch it. Otherwise, let the caller worry about it. If no callers can do anything about it, let the global exception handler catch it, and log it.
I definitely don't use a try catch wrapper around every method (oddly enough, I did when I first started but that was before I learned better ways).
1) To prevent the program from crashing and the users losing their info, I do this
runProgram:
try
{
container.ShowDialog();
}
catch (Exception ex)
{
ExceptionManager.Publish(ex);
if (MessageBox.Show("A fatal error has occurred. Please save work and restart program. Would you like to try to continue?", "Fatal Error", MessageBoxButtons.YesNo) == DialogResult.Yes)
goto runProgram;
container.Close();
}
container is where my application starts so this basically puts a wrapper around my entire app so that nothing causes a crash that can't be recovered. This is one of those rare instances where I don't really mind using a goto (it is a small amount of code and still quite readable)
2) I only catch exceptions in methods where I expect something could go wrong (such as a timeout).
3) Just as a point of readibility, if you have a try catch block with a bunch of code in the try section and a bunch in the catch section, it is better to extract that code to a well named method.
public void delete(Page page)
{
try
{
deletePageAndAllReferences(page)
}
catch (Exception e)
{
logError(e);
}
}
To do it at the point of occurrence, you would still need a try/catch. But you don't necessarily need to catch the exceptions everywhere. They propagate up the call stack, and when they are caught, you get a stack trace. So if a problem emerges, you can always add more try/catches as needed.
Consider checking out one of the many logging frameworks that are available.
I don't think you need to catch everything at the point of infraction. You can bubble up your exceptions, and then use the StackTrace to figure out where the point of infraction actually occurred.
Also, if you need to have a try catch block, the best approach I've heard is to isolate it in a method, as to not clutter the code with huge try catch blocks. Also, make as few statements as possible in the try statement.
Of course, just to reiterate, bubbling up your exceptions to the top and logging the stacktrace is a better approach than nesting try-catch-log-throw blocks all throughout your code.
I would look into using ELMAH for exception handling, which is pretty much a concept of "let exceptions happen". ELMAH will take care of logging them and you can even set it to email you when exceptions for a certain project reach or exceed a specific threshold. In my department, we stay as far away from try/catch blocks as possible. If something is wrong in the application, we want to know right away what the issue is so we can fix it, instead of repressing the exception and handling it in code.
If an exception happens, that means that something isn't right. The idea is to make your application do only what it should do. If it's doing something different and causing exceptions, your response should be to fix the reason it's happening, not let it happen and handle it in code. This is just my/our philosophy and it's not for everyone. But we've all been burned way too many times by an application "eating" an exception for some reason or another and no one knows that something is wrong.
And never, ever, EVER catch a general Exception. Always, always, always catch the most specific exception so that if an exception is thrown, but it's not the type you're expecting, again, you'll know because the app will crash. If you just catch (Exception e), then no matter what type of exception is thrown, your catch block will now be responsible for responding to every single type of exception that could possibly be thrown. And if it doesn't, then you run into the whole "eating" exceptions, where something is going wrong but you never know until it is likely too late.
How does one avoid try/catch in every method, yet still log the error at the point at which it occurred?
It depends on the hosting env. Asp.Net, WinForms, and WPF all have different ways of capturing unhandled exceptions. But once the global handler is passes an exception instance you can determine the point of throw from the exception, as each exception includes a stacktrace.
Realistically, avoid granular try/catches. Allow the exception to traverse upwards in the stack and be caught in as high a level as possible. If you have a specific point of concern, then place logging in the immediate catch, if you are worried about the exception cascading - although you would still be able to resolve these by drilling into the inner exceptions.
Exception handling should not be an afterthought. Make sure that you do it consistently. I have seen a lot of people put a broad try/catch from the beginning to the end of every method and catch the general exception. People think that this helps them get more information, when in fact, it doesn't. More is less in some cases, as less is more. I never get tired of the axiom that "Exceptions should be used to note exceptional behavior." Recover if you can, and try to reduce the number of overall exceptions. Nothing is more frustrating when you are trying to troubleshoot an issue and seeing hundreds of the same NullReferenceException, or similar, when something goes wrong.
Exceptions are implemented so that they have no cost unless thrown.
This means to me that performance ramifications is not a strong argument against. Exceptional conditions usually are ... exceptional.
I have a application with similar code (not written by me)
try
{
EnumerateSomeCoolHardwareDevice();
}
catch (Exception ex)
{
}
UPDATE - This is .NET C# & EnumerateSomeCoolHardwareDevice() is using SerialPort?
I know how bad this code is but it works like this for a reason!
My question thou: I can see that it crashes somewhere in the EnumerateSomeCoolHardwareDevice(); but it doesn't get caught by the Catch (...) - It just crashes with the send report dialog! This also currently only happen in the release build... Is their ANY reason why my exception will NOT be caught by the catch (...)?
My guess is that you're not getting an Exception in your language/framework but rather EnumerateSomeCoolHardwareDevice() does weird things that simply cause the OS to kill your process. Remember that hardware details are abstracted by frameworks like Java and .NET, so whenever you do something with hardware directly, you're probably relying on unmanaged resources ... and whatever goes wrong there can kill you, catch or not.
One possible reason would be if the EnumerateSomeCoolHardwareDevice() function uses threading. If an exception is thrown in a thread and isn't handled within it's thread then it can crash an application. This simple app can demonstrate what I mean:
public static void testThread()
{
throw new Exception("oh god it's broken");
}
static void Main(string[] args)
{
try
{
Thread thread = new Thread(testThread);
thread.Start();
Console.ReadKey(); //Just to make sure we don't get out of the try-catch too soon
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
If you run that the app will crash and burn rather than catching the exception as you might expect.
In .NET catch (Exception ex) will only catch .NET exceptions, not native exceptions.
This question (catching native exceptions in C#) may help.
Assuming .NET, if EnumerateSomeCoolHardwareDevice uses Win32 methods via PInvoke (to access the hardware) and an error occurs, most Native methods return an error code. If that error code is not handled, and another native method is called anyway (perhaps with empty out parameters from the failed call), a serious native error (such as bad memory access or something similar) can cause a straight program crash, no exception thrown.
Have you tried the attribute
assembly:RuntimeCompatibility(WrapNonExceptionThrows = true)
That should wrap any non-.Net exceptions into System.Exception so it will be catched in your code.
If it is only happening on the production machine and not the dev machines then it could be down to DLL mismatches. Double check ALL the referenced DLLs and frameworks are the same version.
Secondly if the error is not being thrown by the EnumerateSomeCoolHardwareDevice() then it will crash the app as there is no way for the exception to get back up the stack (or thats my understanding of try/catches) in my experience this has happened to me before.
Lastly, the microsoft error report usually allows you to inspect what will be sent to MS, this should let you see where the error happened and why (assuming it has readable information within it).
Check the Event Viewer as the error should also be logged there, and normally provides an invaluable source of detail regarding the error and with a bit of digging through the error listed there you should be able to trace the fault.
If you are in .Net version 1.1 use a no parameters catch block like
catch{
...
}
Prior to .Net 2.0 there could be native exceptions that do not derive from System.Exception.
Also hook to appdomain unhandled exception event and see what happens.
There may be a try..catch inside EnumerateSomeCoolHardwareDevice().
If the exception is caught and handled there, the outer exception won't be hit unless the Exception is thrown again.
(Assuming Java) Both Error and Exception are subclasses of Throwable. If there is an assertion failing in EnumerateSomeCoolHardwareDevice() for example you will get an Error.
My guess is that there's a stack overflow happening. The .NET VM simply shuts down Release build processes that encounter a stack overflow, no CLR exceptions thrown. There's probably an internal try / catch inside that function that catches StackOverflowException one way or other, that's why it's not propagating to your code in Debug builds either.
The easiest way to figure out what's going on is by making a debug build, attaching a debugger and instructing the debugger to break before any exceptions are thrown (in Visual Studio, Debug/Exceptions and tick "Thrown" for "Common Language Runtime Exceptions" and possibly other ones as well, in cordbg.exe "catch exception")
If it is crashing madly and is using a SerialPort object then it is probably because at some point it skips onto a background thread and an exception happens here. IIRC the .DataReceived event or however you get information back from a serial port returns data on a background thread. Should an exception be thrown in this routine then the entire application will bail.
Find the background thread and put some exception handling round it.
What types of exception have you seen behaving in this way? Do you have a list of them?
Some exceptions will keep propgating up the call stack, even if they've been caught in a catch block, such as ThreadAbortException.
Others are essentially unhandleable, such as StackOverflowException or ExecutionEngineException.
If it is one of these (or some others I have probably missed), then the behaviour is probably as expected. If it is some others, then a deeper look with more information will be necessary.
Anyway, I'm a little confused about when to propagate an exception and when to wrap it, and the differences.
At the moment, my understanding tells me that wrapping an exception would involve taking an exception like DriveNotFound (in IO) and then wrap it with the general IOException.
But with the concept of propagating an exception, is this only something that happens if I have an empty catch clause? So in an ASP.NET web app, it would propagate to global.asax. Or in the case of a recently deployed web app, an unhandled HTTPException gave a yellow screen of death and wrote a log to Windows Server (this is a web app I'm rewriting). So the exception happens in a method, it could be handled at the class level, displayed in the page, and then goes up to global.asax or Windows Server.
Why exactly do I want to wrap an exception with a more generic one? The rule is to handle an exception with the most specific type (so DriveNotFound for obviously a drive not found). Also, how would I choose between wrapping and replacing an exception?
Is the exception handling chain just the try and catch (or catches) clauses? I assume from the wording, yes.
Finally, why and how would I want to let an exception propagate up the callstack?
I did read the MS PandP guide on exception handling, but I guess the examples didn't engage me enough to fully understand everything.
This question comes from Enterprise Library the ability to wrap/propagate an exception and etc. It's the propagating I'm not sure about, and the differences in replacing/wrapping an exception.
Also, is it ok to insert complex error handling logic in a catch block (e.g. ifs/elses and things like that).
Thanks
No less than 6 questions :-)
But with the concept of propagating an exception, is this only something that happens if I have an empty catch clause?
An exception will propagate upwards until it is caught by a catch block further up the call stack that handles either that specific exception's type or an exception type nearer the base type of that exception's hierarchy. So, for example, all managed exceptions derive from System.Exception, so a catch block that intercepts System.Exception will catch every managed exception.
Why exactly do I want to wrap an exception with a more generic one?
I'm not sure what you mean by "wrap". Do you mean catch an exception, replace it with another, and add the original as the InnerException property of the new exception? Or something else?
I think there's rarely a good reason to replace an exception with a more generic exception. But you can certainly replace an exception with another exception, for one or more of 3 reasons:
To hide implementation details from the caller.
To improve the level of an abstraction so that it's more meaningful to the caller.
To throw a custom exception that's very specific to the problem in hand.
Also, how would I choose between wrapping and replacing an exception?
I'm sorry, but I still don't understand how you're defining these two as different.
Is the exception handling chain just the try and catch (or catches) clauses?
Here are the basics of what happens when an exception is thrown:
The CLR walks sequentially down the list of Catch blocks within the local Try...End Try block, looking for a local Catch block with an exception filter matching the exception that was thrown.
If a local Catch block has an exception filter that matches the exact exception that was thrown, the code in that Catch block is executed, followed by the code in the Finally block. Then execution continues at the first statement following the End Try.
Alternatively, if the exception that was thrown derives from the exception specified by a local Catch block, the same actions happen as described in the second step. For example, an exception filter that catches ArgumentException will also catch exceptions derived from ArgumentException, such as ArgumentNullException, InvalidEnumArgumentException, DuplicateWaitObjectException, and ArgumentOutOfRangeException.
If no local Catch block matches the exception that was thrown, the CLR walks back up the call stack, method by method, looking for a Catch block that wants to respond to the exception. If no matching Catch block is found in the call stack, the exception is considered to be unhandled.
Alternatively, if a matching Catch block is found somewhere in the call stack, the code in every Finally block between the throw and the catch is executed. This starts with the Finally belonging to the Try block where the exception was thrown and finishes with the Finally in the method below the method where the exception was caught.
After this clean-up has been completed for all methods below where the exception was caught, control is transferred to the Catch block that caught the exception, and this code is executed. Next to run is the Finally block of the Try where the exception was caught. Now that the call stack has been unwound and the error clean-up has been completed, the final step is to continue execution at the first statement following the End Try where the exception was caught.
If code within a Catch block causes another exception to be thrown, the original exception is automatically appended to the new exception using the InnerException property. In this way, exceptions can be stacked without any loss of information.
You should avoid placing clean-up code within a Finally block that might throw an exception, unless that code is within its own Try block. Without this added protection, the CLR behaves as though the new exception was thrown after the end after the Finally block and looks up the call stack for a remote Catch block that wants to respond to the new exception. The original exception will be lost unless the original Catch block saved it.
Finally, why and how would I want to let an exception propagate up the callstack?
Why: Whenever you don't specifically understand the exception and know how to recover from it, you should let it propagate upwards.
How: By only catching exception types that you understand and know how to handle. Occasionally you need the details of any exception in order to do a proper recovery. In this case, you can catch it, do the recovery, then re-throw it by using the throw; statement.
Also, is it ok to insert complex error handling logic in a catch block (e.g. ifs/elses and things like that).
Generally yes, because any new exception caused by code in your Catch block will have the old exception automatically attached to it via the InnerException property. But it's not wise to provoke this mechanism if you can avoid it, so the simpler code you have, the better. Another good reason to keep your Catch code simple is that it often won't go through the same degree of testing as your main-line code.
There is already a rather good question about this with lots of good answers and discussion. See here:
Best Practice for Exception Handling in a Windows Forms Application?
It's all about conveying the right meaning to your callers. I doubt there's cause to wrap a specific exception in a more generic one - that helps no one.
Consider an API that has nothing to do with file access but accesses a config file behind the scenes. If the config file is not present you might wrap the FileNotFoundException in a ConfigurationException so that the correct problem is conveyed to callers.
why and how would I want to let an
exception propagate up the callstack?
You would let an exception propagate if you can't handle it. It's that simple. If there is nothing your code can or should do to work around the exception, then let it propagate. When propagating, be careful how you do so:
throw ex;
is different to:
throw;
The former throws away the old stack trace and creates another from the point the exception is thrown. The latter preserves the original stack trace.
Of course, if you can't handle the exception then you might not bother to catch it in the first place (maybe you want to log though).
I usually do this:
Business logic assemblies (dlls) don't handle exceptions unless they are FULLY understood
Exceptions that are expected but not handleable are wrapped in a single exception type and are allowed to roll up the call stack (i.e., all the different exceptions that can happen during a database interaction are wrapped in a single RepositoryException and thrown)
Unexpected exceptions are allowed to propagate (never include a catch(Exception ex) in a dll)
Exceptions are handled only at the last possible moment (i.e., controller for the UI)
Its usually only far up in the call stack that you know exactly what you're doing (what the current business process is) and how to handle exceptions properly.
This is the best resource I've found for implementing a coherent exception handling strategy in .NET
http://msdn.microsoft.com/en-us/library/cc511522.aspx