As far as i know, when a first chance exception occurs, the debugger is notified(if any) and then if still unhandled, the system searches for the nearest frame based exception handler in the stack if any.
I was reading this link when I came to know about vectored exception handling.
Question1) I was wondering if there is any way we can do that in managed code?
Question2) I think that any try{}catch{} is a frame based handler but what happens when we register a handle at certain events like
AppDomain.CurrentDomain.UnhandledException += (x, y) =>
{
Console.WriteLine("Unhandled exception");
};
what are these?
The debugger is only notified of an exception if it is attached. For example, if you are debugging in Visal Studio, then it would be called first, and if it passed on the exception, the exception handlers would be called. To have the debugger stop on all exceptions, from Visual Studio select the Debug menu and select Exceptions and then choose the exceptions you want the debugger to halt at. If none of those handlers (or there are no handlers) then the debugger would be called a 2nd time to stop execution and display a general message that an exception had occurred. If on the other hand, the debugger is not attached, then the debugger won't be notified - which is the case for 99%+ of all managed production code.
Vectored exception handling is a low level api intended to be used from unmanaged code - i.e. C++. Your very first choice from managed code (C#) should be to use structured exception handling with try/catch/finally blocks. Most (99%+) managed code developers using a language like C#, including myself, have found structured exception handling to be quite adequate.
If you still think you need to use this api, you will have to call AddVectoredExceptionHandler by using P/Invoke, which is one way unmanaged code can be called from managed code. There are a couple of caveats. See this link for a general overview. Mike Stall's blog suggests avoiding vectored exceptions in managed code. In this thread, Mike Stall says that unmanaged vector exception handlers should never call back into managed code. He also suggests that managed exceptions are an undocumented feature in vectored exception handling and that MS could eliminate that support in a future release of the CLR, so use at your own peril.
The AppDomain.UnhandledException event is only called when no other handler is found. It could be used in situations where it is desired to log some information about an unhandled exception, but there is little time to put in proper structured exception handling to a large base of existing code, or perhaps you don't have access to the code that is throwing the exception. Otherwise, try/catch/finally blocks should be used instead.
You might also try taking a look at the AppDomain.FirstChanceException event, which occurs before the first exception handler is called. This one might be useful if all you want to do is log some information for certain exceptions thrown in someone else's code that you don't have access to that are handled. It is only a notification though, and not an exception handler. I have never used it before, so don't know how much it might affect performance. My concern here is that Microsoft developers sometimes throw exceptions in the CLR for various things other than true errors. To see this in action, try setting the debugger to break on every exception, including the CLR Runtime exceptions. This can be done in Visual Studio from the Debug menu and choosing Exceptions. So, I don't know how much of an impact it would have on performance since all the CLR exceptions will probably raise this event as well. To be fair, the last time I did this was with VS 2008. This might not be true or as true with later versions of the CLR. I don't see a way to limit the exceptions this event will fire either. So, you would need to filter out the exceptions you are not interested in and experiment to guage its impact on performance.
Related
So I have been doing some research into how I should be doing try-catch-finally blocks and there is some conflicting information in every post I read. Can someone clarify?
One common idea is to not catch exceptions that you do not know what to do with at that point in the code. The exception will bubble up until it presumably gets to a global exception handler if nothing else catches it. So at that point you display a message to the user that an unknown type of exception occurred, log it, etc.
Now after reading it sounds like this is the only exception handler that you will need? You should not be using it for flow control, so you should be checking if something is returned as null or is invalid causing the exception and correcting it in code. ie. testing for null and doing something about it before it can cause the exception.
But then there are other things such as running out of memory that you would not be able to test for, it would just occur during an operation and the exception would be thrown. But I would not be able to do anything about this either so this would be bubbled up to the global handler.
I think there are some that I am missing, like when dealing with files there can be some thrown from the external code. File not found exception seems like one that may come up often, so I would catch it and in the finally block gracefully close down anything I opened related to other code/processing and then notify the user and log it right there?
The only reason why you would want to catch an exception is for the finally part of the block to make sure that whatever you started before the exception is closed/finalized in a known state? But even then you would want to throw this exception after performing these tasks so the user is notified by the global exception handler, there is no point duplicating this code at this point?
So other than a global exception handler you would have try-catch-finally blocks for these scenarios.
So assuming that I am missing something here, there may be the possibility that you want to try and catch a specific type of exception and then do something with it. I cannot think of anything that you would want to do in the catch block though since the global one would log/notify the user and if you have an exception that usually means that there is no deal for the code to continue on.
Is there any easy way to know which exceptions will be thrown from which modules? I think the only way I have read is to read the MSDN or component suppliers documentation, other than that there is no way to know what exception you would be trying to catch if you were looking for a specific one (not sure why you would)
This question came up since in my application I had a section of code in a try-catch block, and it ended up that when an exception occurred it was either because an object was null, or a string was invalid. Once I wrote code to handle those scenarios the try-catch block is no longer needed, if an exception is encountered now there is nothing the code can do to recover so it should be logged and let the user know so it can be fixed.
But this goes against what I have been reading and what has been preached to me, bad code is code with no try-catch blocks. So how does this all tie together and what piece am I missing here?
The first part of your question is all correct: you should only catch exceptions that you know how to handle. Otherwise, just let them bubble up until they reach code that can handle them.
(Note that "handle" doesn't mean "log" or "display an error". It means to correct the problem that caused the exception, or work around it in some way.)
If they never encounter code that can handle them, or if they are unhandlable exceptions (like OutOfMemory), then they will eventually reach the global unhandled exception handler. This is where you will log the exception (if appropriate), display a generic error to the user (if appropriate), and more often than not, terminate the application. You cannot simply continue as if nothing happened—the exception indicates that the application is in an unexpected state. If you try and continue, you're just going to crash, or worse.
I think there are some that I am missing, like when dealing with files there can be some thrown from the external code. File not found exception seems like one that may come up often, so I would catch it and in the finally block gracefully close down anything I opened related to other code/processing and then notify the user and log it right there?
FileNotFound is a good example of an exception that you will want to handle locally. In the same method (or perhaps one level up, in your UI code) that attempts to load the file, you'll have a catch block for FileNotFound exceptions. If appropriate, display a friendly error message to the user and ask them to choose another file. If it's internal code, give up and try something else. Whatever you need to do. There are few good reasons for FileNotFound to bubble up outside of your code.
This is sort of like using exceptions for flow control, but unavoidable. There is no way to avoid using exceptions (or error codes) for I/O, so you just need to handle the failure case. You could try and verify that the file exists first, before trying to open it, but that would not solve the race issue wherein the file gets deleted or becomes otherwise inaccessible between the time your verification code runs and when you actually try and open it. So now all you've done is duplicated your error-handling code in two places, which serves little purpose.
You have to handle exceptions like FileNotFound locally. The further away from the code that throws, the less likely you can do anything reasonable about it.
Another good example of this, aside from I/O-related exceptions, is a NotSupportedException. For example, if you try to call a method that isn't supported, you might get this exception. You will likely want to handle it and have code in the catch block that falls back to a safe alternative.
The only reason why you would want to catch an exception is for the finally part of the block to make sure that whatever you started before the exception is closed/finalized in a known state? But even then you would want to throw this exception after performing these tasks so the user is notified by the global exception handler, there is no point duplicating this code at this point?
This does not require catching the exception. You can have a try block with only a finally block. A catch block is not required. In fact, this is precisely what using statement implements. If you have state that needs to be cleaned up in the event of an exception being thrown, you should implement the IDisposable pattern and wrap usage of that object in a using block.
Is there any easy way to know which exceptions will be thrown from which modules? I think the only way I have read is to read the MSDN or component suppliers documentation, other than that there is no way to know what exception you would be trying to catch if you were looking for a specific one (not sure why you would)
Precisely. This is not really a problem, though, since you are only catching the exceptions that you can do something about. If you don't know that a module can throw a particular exception, you obviously can't have written code that can handle that exception.
The documentation will tell you all of the important exceptions that you might need to handle, like FileNotFound, SecurityException, or what have you.
This question came up since in my application I had a section of code in a try-catch block, and it ended up that when an exception occurred it was either because an object was null, or a string was invalid. Once I wrote code to handle those scenarios the try-catch block is no longer needed, if an exception is encountered now there is nothing the code can do to recover so it should be logged and let the user know so it can be fixed.
Avoiding exceptions in the first place is always the best option. For example, if you can design your application so that a null object or invalid string is impossible, great. That is what we call robust code. In that case, you don't need to catch these exceptions because there's no way that you can handle it. You thought you already handled the problem, so if an exception is getting thrown anyway, it is a sign of a bug. Don't gloss over it with a catch block.
But sometimes, catch blocks are still necessary, and you write code inside of the catch block to handle the problem. In that case, there's probably no reason to re-throw the exception or log it, so you don't have any code duplication.
But this goes against what I have been reading and what has been preached to me, bad code is code with no try-catch blocks. So how does this all tie together and what piece am I missing here?
Completely wrong. I don't know where you've been reading that, but it is nonsense. Exceptions are exceptional conditions. If your code has catch blocks strewn all over it, that is a sign that you are doing it wrong. Either you're using exceptions for flow control, you're swallowing exceptions in a misguided attempt to "improve reliability", or you don't know about the global unhandled exception handler.
Doesn't sound like you're missing anything to me.
The only thing I feel compelled to mention that doesn't fit strictly into any of your questions is that sometimes you might want to catch an exception and rethrow it as a different exception. The most common situation where you would do this is if you were designing a library of re-usable code. Inside of the library, you might catch internal exceptions and, if you cannot handle them, rethrow them as general exceptions. The whole point of a library is encapsulation, so you shouldn't let exceptions bubble up that the caller cannot possibly do anything about.
There is no true guide for exceptions management (raising and handling). Every app has to decide what level of flow control should be used and how exception has to be raised/handled.
General rules are:
exceptions are raised in exceptional situations
handle exception you can handle and do meaningful things for your app so
exception raising can be used in flow control, actually it's the only way you can reliably handle flow control when you are dealing with devices, so hardware interrupts. (printers, bill validators, file transfer...)
The rest is up to you. The meaning of exception management is made by you.
Imagine you need to download some files from an FTP server, one you don't control. Of course you can't trust other people so you need to prepare for temporary outages and such. So you wrap your downloading code in a try-catch-block and look for WebException if you catch one you might check for FtpStatusCode.ActionNotTakenFileUnavailableOrBusy if that was the error you simply retry. Similarly if you call a web service a 404 might be trouble, but a 429 means that you wait a little and retry, because you had been rate-limited.
Usually you can know which exceptions can be thrown by experience or documentation but C# lacks checked exceptions. Things like NullPointerException or ArgumentNullException can be properly handled with guards in your code. But other things, like errors external dependencies can sometimes be caught and handled by you without crashing the application.
Possibly an obvious question to some but couldn't find a duplicate.
I'm packaging the final version of a Windows Forms solution I've been working on and am getting it ready for online distribution. What are the best practices when doing so? We've already had some trouble with packaging the installation file and have run into hurdles to test the program on different PCs, both 32 and 64-bit included.
More specifically, should "throw;" commands be commented out or left in the final release? Would this expose any of the inner workings of the solution itself?
Released application should not crash when exception occurs. You will want to inform the user, something went wrong and log your exception, but you do not want to crash! Informing user should be done in a friendly manner and not just by putting exception.ToString() into the message box.
It is a good practice to add Application.ThreadException or AppDomain.CurrentDomain.UnhandledException handlers to handle all exceptions in your Application. How exactly to do that, is answered in the following thread: Catch Application Exceptions in a Windows Forms Application
However, make sure that your application survives in a usable state, i.e. handle exceptions in a proper way for your application.
I usually add a preprocessor directive for handling exceptions on the application level, since I want them to trow while debugging. For example:
#if !DEBUG
Application.ThreadException += new ThreadExceptionEventHandler(MyHandler);
#endif
It should also be mentioned, that if you have code pieces where you anticipate that Exception might occur, such as network communication error, you should handle those pieces explicitly. What I am saying is, we should not completely forget about exception handling, just because we configured an unhandled exception handler on the application level.
Keep all of your exception handling intact.
Add an event to the starting form in the application, attaching to the Application.UnhandledException event. This will fire if an exception propogates up the stack.
This is the point to inform the user that the application has crashed. Log the error here and then abort gracefully.
Your point about revealing internals, thats up to you to decide. You can obfuscate the source code if you wish, but if you are releasing in Release build mode, and you are not providing the .PDB, then this is the first step.
Ultimately, the DLL / EXE can be decompiled anyway, so its up to you. Debug mode will reveal a lot more than Release mode, but not much more.
Ideally, you should be catching anything that's thrown higher with throw;. Carefully check your code and try to ensure that thrown exceptions are dealt with appropriately. Unhandled exceptions are logged - you can see this information in the Windows Event Viewer. Depending on what details you put in them, unhandled exceptions could give clues as to the inner workings of your application. However, I would suggest that unhandled exceptions are a poor source of information, and that anyone who wanted to know how your application worked could simply disassemble it, unless you've obfuscated it.
Some exceptions cannot be caught by surrounding code with try/catch blocks, so your application should also implement an unhandled exception handler. This gives you the opportunity to show the user an error message and do something with the exception - log it, send it to support, discard it, etc.
As far as I know, you are supposed to only use try/catch when you will actually handle the exception and not just report&log it and then crash the application. Otherwise, you are better off just checking different scenarios where it makes sense (e.g. if sth==null) or - if your purpose is just to log the exception and crash the application - to use AppDomain.UnhandledException. But is this always the case and why?
Suppose the following method, which accepts an array and returns MemoryStream after doing some database and filesystem operations.
MemoryStream Read (int[] IDs)
{
try
{
using (SqlConnection connection = new SqlConnection(connection_string))
{
connection.Open();
// a bunch of code executing SQL queries & constructing MemoryStream, which is returned at the end of the block
}
}
catch (Exception e)
{
// report the exception to the user & log it
throw; // pointles??
}
}
There are multiple situations that can be considered exceptional/unwanted behavior, such as:
argument (IDs[]) being null,
failure to establish an SQL connection,
failure to execute a specific SQL query.
All these cases are considered exceptional, still putting everything inside a try/catch if you only want to log an exception (then crash) is probably bad practice - but why? What would be the best handling behavior in the above case? Avoid try/catch completely, check null references using an if statement (return null in such case) and use AppDomain.UnhandledException to log everything else? Use try/catch, but still check for null references inside using if statements (and return in that case)? Something else?
Peppering your code with try/catch statements only to crash the app isn't productive. The CLR already takes care of that for you. And you've got AppDomain.UnhandledException to generate decent information to diagnose the cause.
Only in the very specific case that you have to clean up something, say a file that you don't want to keep laying about, should you consider writing a try/catch. Which in itself is a very iffy requirement, there is no guarantee whatsoever that your catch block will execute. It will not when the exception is nasty like StackOverflowException or ExecutionEngineException. Or the more common reason that programs don't clean up after themselves, somebody tripping over the power cord or killing the process from Task Manager.
you are supposed to only use try/catch when you will actually handle the exception and not just report & log it and then crash the application
I agree with the first part, although I would add that adding logging at the tier boundaries is valuable when you may not have control over the calling tier. e.g. I log all exceptions that occur in a Web Service at the top method to ensure I have logging on the server since debug info (stack trace, etc) does not always cross comm layers gracefully
In your particular example I would check for "exceptional" conditions where you can but let other exception occur "naturally". For your specific examples:
argument (IDs[]) being null,
failure to establish an SQL connection,
failure to execute a specific SQL query.
For the first one, I would check for null arguments for one reason: A NullReferenceException gives you no context about the cause of the exception, other that where it occurs. I much prefer to check for null and then throw a new ArgumentNullException exception since you can add which argument is null. You may still need to do some digging to find out why it's null but it saves you a lot of time in debugging.
SQL Exceptions can typically bubble up naturally, since they have decent error information in them (e.g. "undeclared variable '#arg'")
I've recently began reading up on this topic myself. My basic understanding is:
Only catch an exception if you plan to handle it.
Overuse of try/catch can lead to exception swallowing and/or the loss of valuable stack trace information and can lead to maintainability issues (what if you decide to standardize your errors/logging?). Instead use try/finally or using blocks to implement clean up.
Catch exceptions at the boundaries via a global exception handler.
Use AppDomain.UnhandledException for exactly what the name implies: logging unhandled exceptions. If you do not log these you'll only find a CLR "Windows Error Reporting" entry in the log viewer and a few dump files that are really of no use to you. It's always a good idea to utilize AppDomain.UnhandledException so if your application does crash you know why.
It's important to note that "handling" an exception doesn't necessarily mean clean up or retroactive logic. Handling could simply mean formatting an error to something more user-friendly or to hide a sensitive stack trace you wouldn't want just anyone to see. I routinely log a detailed error and return a formatted one.
Again, this is just what I've gathered initially. Below are some sources:
Good Exception Management Rules of Thumb
Understanding and Using Exceptions
I am using windows service in c# for file transfer using sFTP (ssh.net).
I have handled exception in each and every block of code still i am getting unhandled exception and my my windows service gets crashed.
i figured out about unhandled exception by using
AppDomain.CurrentDomain.UnhandledException
Is is possible to avoid this unhandled exception and avoid service from being crashed.
Thanks in advance.
Vijay
No, because UnhandledException does not change the fact that the process is going down. It just gives you the chance to do something (e.g. log the failure) before that happens.
Even if things could work like that, the fact is that your service has bugs. You should be looking more to fix them and less to hide them.
Is is possible to avoid this unhandled exception and avoid service from being crashed.
Yes, it is. It is also a bad design decision.
AppDomain.CurrentDomain.UnhandledException
This is a good place to put in a last resort handler that writes a crash report, then restarts the service.
Swallowing exceptions is not smart. EVERY exception you expect has to be handled.
I have handled exception in each and every block of code still i am getting unhandled
exception
Sounds like you do not know what you are doing. It is not necessary to handle exceptions in every code block - it totally overloads your code with exception handlers. It is necessary, though, to have proper exception handling where it makes sense and to catch EVERY SENSIBLE (expectable) exception.
Avoiding the service from crashing is not smart - because if you do not know what exception you have, then you may end up with a corrupt service instead of a crashed one. Fail fast and hard is still the ONLY way to write reliable server systems.
The only way to avoid an unhandled exception is not to have one! Assuming your service doesn't make use of any multi-threading capabilities which could throw exceptions on separate threads, you can get away with putting an exception handler around your ServiceBase.Run call
This way any exceptions that slip through can be caught at the very last minute and handled. Usually though you want to try and grab these lower down and handle accordingly
With threaded applications it becomes a little more difficult as each new thread that is spawned won't throw on the main thread and won't be handled by this 'catch-all' handler.
Edit:
I might add that I don't condone doing this - ideally you should be handling exceptions in the right places - if you are getting unhandled exceptions you aren't expecting, then you need to examine the stack and see what went wrong. Adding a handler to AppDomain.UnhandledException and writing the exception tree and stack to the log will help (you do have some logging mechanism, right?). Either that or debugging
I've found myself doing too much error handling with try\catch statements and getting my code ugly with that. You guys have any technique or framework to make this more elegant? (In c# windows forms or asp.net).
You need to read up on structured exception handling. If you're using as many exception handlers as it sounds then you're doing it wrong.
Exception handling isn't like checking return values. You are supposed to handle some exceptions in limited, key spots in your code not all over the place. Remeber that exceptions "bubble up" the call stack!
Here is a good and well-reviewed CodeProject article on exception best practices.
Java land had pretty the same problem. You just look at method and you can't at a first glance understand what it is doing, because all you see is try/catch blocks. Take a 30-40 line method and throw away all try statements and catch blocks and you might end up with 5-6 lines of pure application logic. This isn't such a big problem with C# as it has unchecked exceptions, but it gets really ugly in Java code. The funny thing is the try/catch blocks were intended to solve the very same problem in the first place. Back then it was caused by errno/errstr madness.
What the Java guys usually do is based on how do you typically handle exception. Most of the time you can't really do anything to correct the problem. You just notify the user that whatever he was trying to do didn't work, put back application in a certain state and maybe log and exception with complete stacktrace to log file.
Since you handle all the exceptions like this, the solution is to have a catch-all exception handler, which sits on top of application stack and catches all exceptions that are thrown and propagated up the stack. With ASP.NET you might use something like this:
http://www.developer.com/net/asp/article.php/961301/Global-Exception-Handling-with-ASPNET.htm
At the same time you are free to override that global handler by placing try/catch block in your code, where you feel something can be done, to correct the problem.
Just adding a Try Catch does not solve the problem. This topic a too big to handle as one question. You need to do some reading.
http://msdn.microsoft.com/en-us/library/8ey5ey87%28VS.71%29.aspx
http://www.codeproject.com/KB/architecture/exceptionbestpractices.aspx
Also FXCop, and VS Team System will warn you on some design issues.
Such heavy reliance on exception handling (in any language) does suggest that the mechanism is being misused. I always understood that exception handling was designed to trap the truly exceptional, unforeseeable event. It is not designed to handle (for instance) invalid data entry by a user - this is normal operation and your design and application coding must deal with such normal processing.
http://msdn.microsoft.com/en-us/library/ff664698(v=PandP.50).aspx
Check out Microsoft's Exception Handling Application Block. It has an intial learning curve, but is good stuff once you get it figured out.