exception handling in c# - c#

i want to know do finally block still execute in exception handling even if there is no matching catch block for the try block and if not then what happens?
Also i want to now system exception and application difference

Yes, you do not need a catch block at all. The finally block always executes.
As to the difference between System.Exception and System.ApplicationException: Exception is the base class for all exceptions; ApplicationException should be used when a non-fatal application error occurs. See the MSDN documentation.
Also see best practices for handling exceptions.

As others mentioned finally will run even if there is no catch block. This supports Java's try finally pattern (which can be achieved using IDisposable and using).
One exception (see what I did there?) is when a StackOverflowException is thrown in which case the finally block will not run (nor would a catch if one were present).
The finally block runs after the try block completes (either cleanly or by throwing an exception) as you would expect from its location in the code.

Related

Unhanded exceptions appear in wrong place if they are thrown from async methods

I created .NET Core console app and added some async magic there. But somehow all exception popups from async methods appear in top-level main method (see screenshot). It makes debugging hard. How i can move them to appropriate places?
How it's now:
I want to move it here:
The debugger will only break when the Exception is unhandled, meaning that there is no further catch block around it. This is also where it will show up in production logs!
Async methods have an "implicit" try-catch around the function. When an exception is thrown in an async method, it is caught and only reintroduced ("re-thrown") into the call stack when the method is awaited (either via the await keyword or through .Result / .GetAwaiter().GetResult()).
This creates a "nice" async call stack that includes the complete flow of the exception over multiple async methods.
As has been mentioned in the comments, you can set the VS debugger to break when an exception is thrown, but this will also break everywhere an exception is about to be handled correctly (it will break before any catch block can run).

How C# Using Statement Translates to Try-Finally

I'm trying to wrap my head around this. According to this page on Using statements:
The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler.
But on this page about Try-Finally blocks it states:
Within a handled exception, the associated finally block is guaranteed to be run. However, if the exception is unhandled, execution of the finally block is dependent on how the exception unwind operation is triggered.
So how can a Using statement be guaranteed to call the Dispose method in the event of an exception if it translates to a Try-Finally that is not guaranteed to call the finally statement?
It really does behave like a try/finally - so if the application terminates, the resource may not be disposed... and that's usually okay, because normally disposal is for releasing resources held by the process... and the OS will tidy those up anyway on process death. (That's not to say the Dispose method won't be called... it's just the same as with a normal try/finally.)
Obviously if you've got a "lock file" on the file system or something like that, that would be a problem - but you'd have the same problem in the face of a power cut etc.
There are exceptions from which a program can't recover, in that case finally block will not execute. For example Stack overflow exception or Out of memory exception.
If the exception unwind only ends with an unhandled exception that crashes the program then finally blocks do not run as execution ceases.
tl;dr
Finally blocks are only run on success or on handled exception.

Where are exceptions best caught?

In a Winforms C# application, it seems like a good idea to catch exceptions in the GUI event methods such as button clicks, since this where all user action in an application begins.
If I put try-catch-finally clauses in the event methods then surely all my exceptions can be caught and dealt with appropriately?
Right?
In general, you should only catch exceptions that you know how to actually handle. You should catch them as close as possible to where they occur (because at that point, you know what the exception actually means).
If you are only catching exceptions in order to log them (and if this is a WinForms application), then I would use the Application.ThreadException event.
There are several ways to do it..
I prefer creating my error handler and throw all the exceptions from the code instead of catching it at that level.
Look at another post on how to handle them via Global Handler:
Where are exceptions best caught?
catches should be placed as close to the throwing source as possible. If your button click calls into your business layer which does some file processing, the business layer will better know how to recover from a FileNotFoundException than your button click handler.
Please check http://msdn.microsoft.com/en-us/library/system.windows.forms.application.threadexception.aspx
public static void Main(string[] args){
// Add the event handler for handling UI thread exceptions to the event.
Application.ThreadException += new ThreadExceptionEventHandler(ErrorHandlerForm.Form1_UIThreadException);
// Set the unhandled exception mode to force all Windows Forms errors to go through
// our handler.
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
// Add the event handler for handling non-UI thread exceptions to the event.
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
// Runs the application.
Application.Run(new ErrorHandlerForm());}
Typically, the best advice is to catch exceptions where they can best be handled, and generally to favor catching them earlier if possible.
The reason is that an exception represents an error state that the code throwing it does not know how to deal with (if it did, then it would have dealt with the error). As a simple example, say you throw a NullReference exception. The coding throwing has no idea why the reference it needs is null. Maybe it's supposed to be, but the code doesn't account for it. Or maybe there's an error in your logic farther up that passes the null down.
Catching everything at the highest level, the UI events, is a good fallback to prevent exceptions from being exposed to the user, but it's a bad practice to get accustomed to because it obscures the real reasons why exceptions are being thrown and makes it difficult to figure out where the error should be corrected at.
yes your are. but Exception is for,
Catch specific exception to general exception.
[updated]
If exception is from different thread then it won't . right point, thanks " Brian Rasmussen" ;)
A try block will operate on any uncaught exceptions thrown by code within the try block. This includes methods you call, any methods those methods call, and so on. If the exception is thrown from one of those methods, it will "bubble up" through the program, breaking out of loops, methods, etc. until it reaches the last (i.e. deepest) try block to enclose it.
You could say that from the time you enter the try block until the time you leave it, any exceptions will immediately break out of the try and have the opportunity to be handled by it (unless they're caught by other try blocks nested inside it).
So to answer your question, if you know any exceptions are going to happen inside the event handler (or in methods called from inside that event handler), then wrapping the whole thing inside a try-catch-finally block will catch any exceptions (assuming an untyped catch).
Whether this is a good idea or not is a question of design. It usually isn't. You normally want to put your error-handlers fairly close to where the error might get thrown. However, without knowing your situation or your code, it's hard to give you any advice on design details like this.
Not to forget AppDomain.UnhandledException. I always handle this one, too, when doing central exception handling.

CLR exits when a thread gets unhandled exception

I have background threads in my application. When one of the threads gets an exception that is not handled the entire CLR exits.
Is it normal behavior, or is it a bug in the CLR?
I would expect that the thread will exit but the CLR will continue working.
The default behavior in .NET applications is to exit whenever an unhandled exception occurs. When an exception goes unhandled, the program is in an unknown and possibly unsteady state. Just because it happened in a background thread doesn't mean that the error won't affect the rest of the program. The most prudent course for the runtime in that situation is to dump the program.
You might look into AppDomain.CurrentDomain.UnhandledException, which will allow you to catch unhandled exceptions and react accordingly. A better solution is to wrap your thread proc with a try...catch. But only have it handle those exceptions it knows how to handle. Doing this:
void MyThreadProc()
{
try
{
// ...
}
catch
{
// handle all exceptions
// This is a BAD idea
}
}
Is a really bad idea, because it can mask exceptions that you really do want to be propagated to the main program.
Your expected behavior used to be the behavior back in 1.1. It was generally considered to have been a bad idea. When you have an unhandled exception in any thread, your process can be left in an inconsistent state. Updates to shared data may be partially applied, etc. The runtime doesn't have the information to safely handle this scenario, or even know how you want to handle this scenario, so its choice would amount to terminating the thread and leaving your program in a strange state. This could lead to resource leaks, hangs, corruption of data, etc. By terminating the process given an unhandled exception you know exactly what happens, the process ends.
This is a normal behavior of the CLR from v2.0. Here is a MSDN post on this. To avoid process from terminating you could use something like this
<legacyUnhandledExceptionPolicy enabled="1"/>
which is not advisable.
It is normal behavior. Perhaps you want to catch the exception to prevent the application from exiting.

Why win32 exception are not caught by c# exception handling mechanism

I have a winforms application.Winforms start with Program.cs where we have main() defined.I have put this code in try-catch block.
[STAThread]
static void Main()
{
try
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new frmSplash());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
if (ex.InnerException != null)
{
MessageBox.Show(ex.InnerException.ToString());
}
}
}
Whenever there is a win32 exception,this mechanism fails and unhandled exception message is thrown and application crashes.
I have 2 questions regarding this code:
1) Why win32 exceptions are not caught.
2) Is it a good practice to catch exceptions at the highest level.
EDIT : as Pratik pointed out, the following answer applies to .NET 1.0 and .NET 1.1 only. Starting with .NET 2.0, non-CLS exception should be caught as a RuntimeWrappedException.
Because Win32 exceptions do not derive from the .NET Exception class. Try :
try {
} catch (Exception ex) {
// .NET exception
} catch {
// native exception
}
See Catch non-CLSCompliant exceptions in general handlers for more information.
The execution of Application.Run is not throwing an error. That is happening on another thread (or at least asynchronously).
Its good idea to inform the user in friendly way that the application has failed before it disapears completely, however its not a good idea to just catch then continue.
While I don't know why your catch block doesn't work try using the Application ThreadException Event. This should catch any error in application threads. Add an event handler before calling Application.Run.
For your second answer definitely yes. I develop and maintain a enterprise winforms application that talk with a web service backend on background threads. If any webservice call crashes handle the application threadexception (and also appdomain unhandledexception) event, log and popup an error that business users can report and allow them to continue without crashing the application.
Try subscribing to these events before your application starts (Application.Run) :
AppDomain.CurrentDomain.UnhandledException.
Application.ThreadException.
You could then get rid of your try catch block.
I think it is bad practice to catch exceptions at the highest level, but you cannot avoid it ! During development (Debug), those exceptions should not be caught and the application should do the nastiest thing possible (crash ?). In production (Release), you will want your application to degrade as nicely as possible even when unhandled exceptions occur. This is one of the few uses I found for the DEBUG preprocessor variable.
You may need to catch as Win32Exception (or ExternalException) instead
http://msdn.microsoft.com/en-us/library/system.componentmodel.win32exception.aspx
I seem to remember that Win32Exception inherits from ExternalException but ExternalException does not inherit from Exception so won't be caught by your code.
Edit: See other answers for why this is wrong!
Edit 2: As for the second part, as stated by AnthonyWJones It is good manners to let the user know that a problem has caused the application to close, however I would recommend using a plain English statement to the user, and logging the exception stack to a log file for your own use.
1) Win32 exceptions should be caught. Maybe the exception is being thrown from a background thread or the GC thread?
2) It depends on your app structure. For example, if your error notification UI was tied to the main form somehow (e.g. you need to invoke the UI thread from a worker thread), then it would be silly to display a UI in a code block outside the code that runs the message loop. However, if your code example is single-threaded then it would be fine.

Categories

Resources