C# exceptions in debug mode vs real - c#

I always thought that in Visual Studio and C#, an unhandled exception leads invariably to program termination. Now I know I can continue. Also when the application is running in the debug mode, I can "skip" unhandled exceptions while once the program is deployed (or how is it called when you make an executable?) it will crash it?

I think these articles would be useful for you to read:
Exception Handling (MSDN)
Handling and Throwing Exceptions (MSDN)
It's better to grasp the basics then decide what fits best for you.

catch(Exception ex)
{
#if DEBUG
Console.WriteLn("oops")
#else
throw
#endif
}

The exception means something unexpected occured. If the application doesn't know how to respond, it would crash.
The reason we have the constructs like try catch finally is to make the application aware of the unforeseen issues and how to react in such cases.
If you implement exception handling properly, your application would always run smoothly. It might come to termination, but even that wouldn't be abrupt.

Related

.NET exception not caught

I have a function that looks like this:
try
{
_dbManager.InsertSearch(some data);
}
catch (Exception ex)
{
//do logging
}
_dbManager uses LINQ to insert data to a SQL database. Yesterday, the machine that hosts the database ran out of hard disk space and my program crashed. I got a crash dump which shows that there was a SqlClient.SqlException raised with an exception message reading something like "Database transaction log is full...".
My question is: Why didn't the exception get caught in the catch block above? The weird thing is, when I tried to reproduce the issue, I could get the same exception, but it was caught by the catch block. What could be the issue?
Second, related question: Imagine if we use a third party library and we don't want any exception thrown. We can use try-catch block, but this only works on calling thread. What if the third party starts new thread and an exception is thrown there? Is there a way to handle this? I know I can register our UnhandledExceptionHandler, but that seems to be a different from what I wanted.
My question is: Why didn't the exception get caught in the catch block above?
As David Stratton suggests, the system might have been out of disk space and not able to write to log file. There is also a chance that the process was terminated due to Corrupted State Exception that will not be delivered to your catch-all block in .NET 4. The exception that terminated process might have also been thrown from the thread that did not have catch-all.
Second, related question: Imagine if we use a third party library and
we don't want any exception thrown.
I think that you will have to stop right there and rethink it. What you saying is that you are absolutely 100% sure that nothing ever can go wrong in the thirdparty library. There are certain exceptions (like OutOfMemoryException) that you should not be catching because your code simply does not know how to recover from them. The rule of thumb with exception handling is that you should only catch the exceptions that you fully understand and know how to recover from. Please take a look at this answer and the links in it.
What if the third party starts new thread and an exception is thrown
there? Is there a way to handle this?
The best way to handle this is to rely on default CLR policy that will terminate your application. The only reasonable thing you can do is try to log it by subscribing to AppDomain.UnhandledException.
Is it possible that there is another try/catch block inside that InsertSearch method, which has conditional throw statement.
The implementer of the 'DBManager' class, chose not to throw in case there is not enough space to write on the disk. Just a thought.
If you use Code contracts runtime checking I advice you to check compiled version of your DLL.
Read this for details Why .net exception is not caught?

C#: should all exceptions be caught

Should all exceptions be caught in a C# program, or are some exceptions (such as stack overflow, out of memory etc.) ones that you should allow the program to crash on because there is no way to recover from them?
You should only catch exceptions that you are able to handle. Never ever catch exceptions and do nothing. Do your best to keep the exception from occurring in the first place. This is especially important in .Net because exceptions incur a penalty in performance due to the stack trace.
It depends on the program, of course, but in general, only catch exceptions that you can actually do something about in a meaningful way.
See this question about catching an OutOfMemoryException (you can usually recover from it) and this one about catching a StackOverflowException (generally not possible).
If you're writing a long-running application (e.g. a web server), then of course you'd want to catch all possible exceptions to prevent them from terminating the entire process. If you're writing a low-impact end-user application, then perhaps just logging the exception and failing fast is the best solution.
It's impossible to be (completely) prepared for the unexpected.
Yes, at the very least exceptions should be logged, giving as much intofmation about the state of the system/program at the time of the crash. The Logging Application Block is one of the more robust automatic ways to log errors.
From commercial application development POV, all exceptions should be caught and NONE should be allowed to crash the program. Because, now-a-days, computer users can differentiate between an error message and application crash dialog.
A product that crashes gives bad impression to the customer. When you have no way to recover, you can show an error message politely saying that the app will exit now and the user has to start the app again. Then, gracefully exit when the user presses ok on the modal dialog.
Even sometimes you can give useful information when there is no way to recover. For example, in case of out of memory, you can advise the user to close other applications (if any) before starting this app again.
Though, the end result is same, but a friendly error message gives much better impression than an OS generated crash dialog.
MSDN article on the topic:
http://msdn.microsoft.com/en-us/library/ms229005.aspx
Highlights:
Avoid handling errors by catching non-specific exceptions, such as System.Exception, System.SystemException, and so on, in application code. There are cases when handling errors in applications is acceptable, but such cases are rare.
An application should not handle exceptions that can result in an unexpected or exploitable state. If you cannot predict all possible causes of an exception and ensure that malicious code cannot exploit the resulting application state, you should allow the application to terminate instead of handling the exception.
...
You should catch only those exceptions that you can recover from.
...
Do prefer using an empty throw (throw;) when catching and re-throwing an exception. This is the best way to preserve the exception call stack.
MSDN Magazine on Exception Handling changes in .NET 4.0 -
"It's Still Wrong to Use Catch (Exception e)" -
http://msdn.microsoft.com/en-us/magazine/dd419661.aspx#id0070057
When you think that there might be an issue arising from user interaction with your app in an unintended way, then you must always catch a possible exception, and handle it with relevant error messages.

C#: what happens if an exception is not caught

What happens in a C# program if an exception is not caught. Does the program 'crash' with something like a run-time error?
What happens in a C# program if an exception is not caught. Does the program 'crash' with something like a run-time error?
Maybe.
Maybe not.
What happens is implementation-defined.
For example, you might get a dialog box that says "there was an unhandled exception, and I see you have Visual Studio installed. Do you want to start up the debugger and examine the program state?"
You might get a dialog box that says "there was an unhandled exception, do you want to report this to Microsoft?"
If you are already running in the debugger, the debugger probably does something to bring it to your attention.
The runtime is allowed to do whatever it wants, and that includes asking you what to do.
Note that the runtime is aware of whether there's going to be a catch block or not before the finally blocks run. You can easily demonstrate this with a console app. Write an app that crashes, and outputs in the finally block:
Unhandled Exception: System.Exception: Exception of type
'System.Exception' was thrown at
ConsoleApplication1.Program.Main(String[] args)
finally running now
See what happens? The runtime reports the error, gives the debugger a chance to run, or reports the problem to Microsoft, or whatever, before it runs the finally blocks. If they run at all. They might not. Anything can happen. The user could decide to destroy the process, or start a debugger and fix the exception, or whatever.
If you really want to understand how exceptions work in C# you should read this:
http://blogs.msdn.com/b/cbrumme/archive/2003/10/01/51524.aspx
Yes.
Yes.
Something "exceptional" has happened, and your program does not know how to handle it, so it must stop execution at that point and "crash". There will be code that is executed after the crash, such as finally blocks, but basically the party is over for your code.
The best thing to do is to log these events, giving as much intofmation about the state of the system/program at the time of the crash. The Logging Application Block is one of the more robust automatic ways to log errors.
Try it! Depending on the error, it will usually catch. Now, as for should all exceptions be caught, if its something like a[i] where it COULD throw an error if i is too big, but you knew that i was supposed to be kept within bounds (for example, in a for loop), you would not catch that exception.
However, if you are using data coming from a user (say, from a GUI) you would almost always validate it.
Try it yourself!
class Program
{
static void Main(string[] args)
{
int[] arr = new int[1];
arr[5] = 6; //throws an exception; what kind?
}
}
Compile and run this in debug mode for a quick answer to your question.
Or just write some programs. Sooner or later, your code will throw exceptions; it happens to all of us, usually more times than we can count. In console or WinForms applications, an unhandled exception will usually crash the program; in ASP.NET, it will generate an error page, but it won't crash the whole website. You can also write custom code that specifies what to do in case of an unhandled exception, so that your application will fail gracefully.

C# create a fatal exception?

I have a strange scenario when my application can get into an infinite loop when shutting down. It occurs when it wants to do something but the calls fail as it no longer has access (time based). In such a scenario it should just stop.
I record failed attempts and if the count goes above a certain number in a certain time I throw an exception which I expect to start the JIT debugger and stop the application.
I am not entirely sure why it gets into the loop so I want the JIT window that gives me information like the call stack and application status.
I have exception handling, but what I want is to turn it off and somehow generate an exception that will trigger the JIT debugger, however, all other posts I have found have been for handling exceptions and avoid crashes.
If there is another way at runtime to have the application stop and tell me what is happening I would like to know.
Thanks.
You should try Debugger.Launch() and Debugger.Break() methods (but remember that you should use them only in development environment). You can read more here: http://msdn.microsoft.com/en-us/library/7kzs2ysh.aspx
This line:
System.Diagnostics.Debugger.Launch();
will launch the debugger for you. Give it a try.
I have exception handling
Sounds to me that you have too much of it. Only ever catch specific exception types, never catch Exception. Now you can simply throw any other exception type and your app will bomb with an unhandled exception. Which brings up the JIT debugger dialog on your dev machine, a merciful end on your customer's machine.
Using System.Diagnostics.Debugger is good too, but wrap it with #ifdef DEBUG. Your customer doesn't have one.

How to get rid of exceptions thrown by the .NET Framework

In a recent project I'm using a lot of databinding and xml-serialization. I'm using C#/VS2008 and have downloaded symbol information for the .NET framework to help me when debugging.
The app I'm working on has a global "catch all" exception handler to present a more presentable messages to users if there happens to be any uncaught exceptions being thrown. My problem is when I turn on Exceptions->Thrown to be able to debug exceptions before they are caught by the "catch all". It seems to me that the framework throws a lot of exceptions that are not immediately caught (for example in ReflectPropertyDescriptor) so that the exception I'm actually trying to debug gets lost in the noise. Is there any way to get rid of exceptions caused by the framework but keep the ones from my own code?
Update: after more research and actually trying to get rid of the exceptions that get thrown by the framework (many which turn out to be known issues in the framework, example: XmlSerializer giving FileNotFoundException at constructor) I finally found a solution that works for me, which is turning on "Just my code" in Tools >> Options >> Debugging >> General >> Enable Just My Code in VS2008.
You can fine tune which types of exceptions are caught in which way through the Exceptions dialog in VS2008, but If the frame work is throwing "a lot of exceptions" you might want to look into that as well. Just because an exception is handled doesn't mean that it's safe, or that it's not robbing your performance.
One way to filter exceptions thrown by the framework is to derive your own exception classes from Exception. You can then use multiple catch blocks:
try
{
//your code here
}
catch (MyAppException myEx)
{
//Do something with your custom exception
}
catch (Exception ex)
{
//Do something (or nothing) with an exception thrown by the Framework
}
It might be worth your while to get rid of catch-all exceptions as it is not exactly good programming technique. For an example, if you are working with Input Output such as file reading/writing, trap the IOException instead of the more generic Exception, another example is XmlException for any XML manipulation. Using a catch-all generic Exception may yield a performance hit as the specific exception has to "bubble up" up to the generic Exception Handler.
Hope this helps,
Best regards,
Tom.

Categories

Resources