How can I execute some code when my program experiences a fatal error and crashes? For example, something goes wrong and the box pops up that say "TestApp.exe has encountered an error and needs to close." and then I want to write to a file with an error code and say a report of the last few things that were entered into the program. How would I do this in C#??
Depending on the type of application you are writing there are different ways. You may take a look at the following article to see how this could be achieved in a WinForms application.
Generally it's a bad idea to write handlers for Exception, FatalException and two more types, you should be more specific in try.. catch clause. Try explore the Application class, especially its SetUnhandledExceptionMode. You can find a nice example on how to use it here.
It depends on what you are asking here.
Regular exceptions you can get through try/catch.
However if you are running any external dll that may for example get Corrupted state exceptions (CSEs) you need to enable legacyCorruptedStateExceptionsPolicy in your app.config (but dont forget that there is a reason for Microsoft to remove this as default as it was before. You should try to fix this kind of errors not only catch them and forget them)
http://dotnetslackers.com/articles/net/All-about-Corrupted-State-Exceptions-in-NET4.aspx
For logging errors to the file you may use log4net
Any way it should look like:
try
{
// Something potentially dangerous
}
catch (Exception Ex)
{
Logger.Append(Ex.Message);
}
Related
I'm developing a web application in C#, and I have a special exception type, that I need to have a full log from its happenings, and of course I'm going to handle that to show a special message to the user or something.
The question is, is it a good practice to write logging codes inside exception's constructor? I'm asking this because I have not seen something similar to this before.
Thanks in advance
A short and good answer should be: no, you shouldn't go this way becuase you want to develop your code with a good separation of concerns: exception handling isn't logging, thus, logging can't be part of constructing an exception.
If that exception is not handled by your code, you can use a last-chance exception handler like AppDomain.UnhandledException event and log it there.
According to MSDN, it is a bad practice to catch exceptions without a specific type and using for example System.Net.Exception
Do I have to dig into the msdn manual to see the possible exception types each time I'm going to catch an error. Or is there any way in the IDE to let me see this quickly.
Currently I'm using Visual Studio 2013 Express Edition
try
{
using (WebClient goog = new WebClient())
{
goog.DownloadString("http://google.com");
}
}
catch(Exception E)
{
saveLog("methodname", E.Message);
}
EDIT :
In this link, it looks like VS already has an option to display exeptions, however, when I'm selecting a method, it only shows the type, and the parameters of the method. But it doesn't show exceptions
The best practice is, generally, to only add handling for exceptions you expect to occur during the run-time of your program.
If you're dealing with files, for example, handling the ***NotFoundException types makes sense. Proper coding will ensure things like ArgumentNullException don't happen, so that doesn't need handling, etc.
Unlike Java, C# does not need to list your potential exeptions in the signature of your methods. This has some good sides and some bad sides. You just encountered one of the bad sides.
You cannot know what exception might be thrown unless
The method you are calling is well documented with its potential exceptions listed (best case)
You know the specific bad cases, run them and see what exceptions they create (bad case)
You have no idea what could go wrong and log everything, modifying your catch every time something unexpected happens (worst case)
There's no built in feature to show this automatically but you put the caret somewhere in the method name and press CTRL and Space. The information shown here will be the same as that in your link, so it should show two exceptions for the DownloadString method.
Hovering over DownloadString won't necessarily show you the same information as clicking on the method name and pressing CTRL and Space (the latter showing you the exceptions being thrown by the method).
Recently I looked at some coding at the web. I found some people use Microsoft.VisualBasic.CompilerServices.ProjectData.ProjectData class in catch block.
catch (Exception exception1)
{
//ProjectData.SetProjectError(exception1);
Console.WriteLine(exception1.ToString());
Console.WriteLine();
Console.WriteLine(sSQL);
//ProjectData.ClearProjectError();
}
I searched it on msdn that mentioned that this API supports the .NET Framework infrastructure and is not intended to be used directly from your code.
I am curious what reason people use it. Would you explain it to me?
My experience has been that this type of code use is found in c#/VB.NET projects that have been converted from VB6. When developing new c#/VB.NET solutions/projects, this practice should not be used.
Note: This technique can safely be replaced with proper exception handling that you would be used to seeing in other .NET solutions/projects.
This code is either emitted by a code conversion tool that converted VB code to C#, or resulted from decompiling an assembly that was originally created using VB.
I'm porting a VB project to Mono, and found out that the VB compiler injects these calls ProjectData.SetProjectError(exception) and ProjectData.ClearProjectError() in any catch block, and try to find a way to prevent the compiler from doing so because Mono doesn't implement the ProjectData module. And found your question while doing my research!
so this is a result of old legacy vb6 for those interested. when vb6 started out there was an err object which is still around but has moved to the projectdata object in vb. if anybody like me remembers vb6 ( this is back when dinosaurs roamed the earth), there was a handy little call on error resume next. this is if you did not like those pesky little exceptions. most vb6 programs used it copiously and voila you had no exceptions because you ignored any. so here comes the explanation.
catch (Exception exception1) // catch any exceptions that just happened
{
ProjectData.SetProjectError(exception1); // set the information
//in the err object if anyone actually wants to check
ProjectData.ClearProjectError(); //clear the err object
}
as you can see this is completely ignoring any exceptions and in true vb6 fashion, your code just explodes without any explanation. needless to say if anyone writes code like this or uses vb in this way, I will find you and figure out a way to get you incarcerated.
In our app, we use components developed by other teams. The question was how can I define a nicely way of exception handling than this
try
{
someComponent.DoStuff();
}
catch (Exception ex)
{
textLabel= ex.Message;
}
The component has no custom exception type, maybe a nicely way to do it would be to define a component specific Exception type and wrap this somehow?
I know the question is very basic, but I am interested more in the let's say how it is good to do it. If you call another component with no custom defined exception types, how do you handle any potential exceptions in an elegant way?
Ideally you would have the component development team do this for you - how else do they expect their clients to recognize and handle errors from their component? Scoping the exceptions that a component can raise is a fundamental part of good C# design.
If that's not an option, then implementing your own wrapper on top of the component to taxonomize its failure cases sounds like a good second best, and very noble of you into the bargain.
If the third-party library is poorly documented (they don't specify the exceptions that can be thrown by each method), there are tools available that can Reflect into the code and determine the possible Exceptions that may be thrown. This can get a bit daunting (there are a surprising number of exceptions that can be thrown for any given call), but it's better in principle than catching the general Exception type. Here is one commercial product that performs this type of analysis.
When you catch an error you are able to repackage it and then throw another error, at the most basic level you may just be adding more data - but, from what you've suggested, you could also replace the generic error with a custom error that, whilst it won't overcome the limitations of the response you've got from the component, would give the code further up the call stack the opportunity to respond more appropriately.
So in terms of just adding information in the most basic manner - by throwing a new exception with some additional text whilst still passing the original exception:
catch (Exception ex)
{
throw new Exception("This is more about where the exception occurred", ex);
}
Now, if you want to define your own custom component exception you change the new Exception to new ComponentSpecificException adding data as necessary to the constructor but never forgetting to set the inner exception. Exceptions also have a data collection of key, value pairs into which you can insert more information (by creating the exception, adding the data and then doing the throw).
That's all fairly generic - working forward from there, where you can't necessarily anticipate all the exceptions you have to handle you don't try - you set up logging so that you know when you've got a generic exception i.e. one that hits the final catch - and then over time add exception specific catches above the generic to provide more appropriate responses or, at the very least, package up the error into less general custom exceptions.
Not sure I've explained that very well - but the notion is that as its difficult to anticipate every possible error you want to have a strategy to develop your application in a systematic fashion as you discover new exceptions.
Assuming you want to catch every type of exception, this solution looks fine to me.
Either from your knowledge of using the component, or by using something like Reflector to analyze the compiled component, what possible exceptions can this component throw? Would providing exception handlers for these allow you to provide better feedback to you users?
The only reasonable (much less "elegant") way to handle exceptions is to log them if you can't recover from them.
Then notify the user there was a problem and offer them the chance to try again (if it's an interactive program).
If your application is exclusively for .NET developers, go ahead and show them the exception message (though Exception.ToString is better, since it includes a stack trace). Otherwise, don't display exception messages in your user interface - that's a security hole and will only confuse your users.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
Why do we need to create custom exceptions in .NET?
Specific customs exceptions allow you to segregate different error types for your catch statements. The common construct for exception handling is this:
try
{}
catch (Exception ex)
{}
This catches all exceptions regardless of type. However, if you have custom exceptions, you can have separate handlers for each type:
try
{}
catch (CustomException1 ex1)
{
//handle CustomException1 type errors here
}
catch (CustomException2 ex2)
{
//handle CustomException2 type errors here
}
catch (Exception ex)
{
//handle all other types of exceptions here
}
Ergo, specific exceptions allow you a finer level of control over your exception handling. This benefit is shared not only by custom exceptions, but all other exception types in the .NET system libraries as well.
I did a lengthy blog post on this subject recently:
https://learn.microsoft.com/en-us/archive/blogs/jaredpar/custom-exceptions-when-should-you-create-them
The crux of it comes down to: Only create a custom exception if one of the following are true
You actually expect someone to handle it.
You want to log information about a particular error
So you can also throw them yourself, and then catch them and know exactly what they mean.
Also: if you're building a class library/framework/api, it's often useful to create a BaseException that other exceptions in your code inherit from. Then when your code raises exceptions the programmers who are using it can quickly know the source of the exception.
Because it can make your intentions clear, and you can also track usages using IDE functionality. Say that you have a custom backend system called "FooBar" and you make a "FooBarDownException", you can track usages of this exception to identify any custom logic your application contains because FooBar is down. You can choose to catch this specific type of exception and ignore others, avoiding overloads and conditional logic within exception handlers. It's really just another version of strong typing. It also means you can avoid comments in your code because the exception has an intention revealing name.
I am not sure why "technically" but lets say I have a app/website that uses permissions. If someone does not have the right permission, its kinda stupid to throw a DivideByZero Exception or IOException. Instead I can create my AccessDeniedException which will help me debug later on.
It's the same reason you would create different exit codes for a non-.NET application: to specify different application-specific errors. Like...ConnectionBrokenException or um...UserSmellsBadException...or something.
This way you can know exactly what went wrong and act appropriately. For example, if you try to send some data and the data transport class throws a ConnectionBrokenException, you can pop up a reconnect dialog and try to reconnect. Then the reconnect method would throw a ConnectionTimeoutException if it times out, and you can again act appropriately.
Another reason, when a client talks to interfaces. Since the client is unaware of the implementations of the interface and since they maybe can throw different exceptions, it's good place to create custom exceptions to uniformise the errors thrown.
I wrote about this special case:
http://blog.mikecouturier.com/2010/01/creating-custom-exceptions-in-net-right.html
As Joel wrote: So you can also throw them yourself, and then catch them and know exactly what they mean.
In addition, you can add specific info about the problem in order to let your exception handler act more accurately.
The standard .NET exceptions don't cover everything bad that can go wrong in any application nor are they intended to. Unless your program is very simple, it's likely you will have to create at least a few custom exceptions.
For one thing, Exceptions are implemented in the Library, not in the language--how can they create exceptions in the library? I'm pretty sure you aren't advocating that system libraries should have a different set of rules.
For another, it's actually possible to use an object tree of exceptions. Your inherited exceptions can have special attributes if you like--they can be used for more complicated things than they are. I'm not advocating they be used as a generic data transport mechanism or anything (although they could be), but I could see a case where someone implemented a custom logging solution that required a special attribute on the Exception...
Your custom exceptions could contain a flag indicating special treatment (maybe one saying you should restart the JVM), they could contain information about logging levels, a bunch of stuff.
Anyway, I'm not advocating this stuff, I'm just saying it's possible. The first paragraph is you real answer.
You shouldn't if the built in Exceptions appropriately describes the problem/exception. I wouldn't make my own base classes to create a custom ArgumentException, ArgumentNullException or InvalidOperationException.
You can create your own exceptions, and describe the error at a higher level. however, this usually doesn't help that much in debugging from a consumer class.
If you throw and catch the exception yourself, a custom exception may be in order.