Exit the application in case of any unhandled exception - c#

[I understand that there are 100's of similar question on the net but I am still not able to find out a working solution to this problem and hence posting it.]
I have a c# Win-Form application. The application is used for downloading images via FTP from another server.
With the help of a task scheduler, the application runs 3 times a day and downloads the images and after that it closes automatically.
It used to work fine last year, however, since the beginning of this year, we are getting unhandled exception like "request timed out" or "operation timed out" from the application.
Thus instead of the application getting closed automatically, it shows a windows dialog with "continue" and "quit" button.
My requirement is that the application should close automatically in case any unhandled exception is thrown.
I have written the following code in my program.cs to handle this. However, this is also not working and I am still getting exceptions window.
[STAThread]
static void Main()
{
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
static void MyHandler(object sender, UnhandledExceptionEventArgs args)
{
System.Diagnostics.Process proc = System.Diagnostics.Process.GetCurrentProcess();
System.Windows.Forms.Application.Exit();
System.Environment.Exit(0);
proc.Kill();
return;
}

There are several events to which you may need to subscribe to ensure that you catch EVERY possible exception:
Application.ThreadException += yourThreadExceptionHandler;
AppDomain.CurrentDomain.UnhandledException += yourUnhandledExceptionHandler;
TaskScheduler.UnobservedTaskException += yourUnobservedTaskExceptionHandler;
And of course you should also have a try/catch around the body of the program:
public static void Main()
{
try
{
runProgram();
}
catch (Exception exception)
{
// Your main exception handler.
}
}
You can have a common exception handling mechanism that all your attached handlers call, to avoid duplicated code. UnobservedTaskException might be something you want to handle differently (log it and otherwise ignore, perhaps).

Dealing with unhandled exceptions is a pain, and usually leads to a loss of context, making it very hard to know what to do next. There are ways of dealing with this gracefully though.
As it happens, I wrote a blog post on the subject just today. This extends the usual exception handling to give you a more robust and predictable execution path.
The way it works is that you wrap any potentially failing parts of the code in something that will catch any exceptions, and wrap them up in a way that you can deal with them. I did this by having an abstract Fallible class that has three inherited classes, Success, Failure and BadIdea. There is a helper method that does this for you, leaving you with an object that either contains the data you want, or an exception that you can use to log the error, report to the user, etc.
The abstract class looks like this...
public abstract class Fallible<T> {
public static Fallible<T> Do(Func<T> f) {
Fallible<T> result;
try {
T fResult = f();
result = new Success<T> {Value = fResult};
}
catch (BadIdeaException ex) {
result = new BadIdea<T> {Exception = ex};
}
catch (Exception ex) {
// NOTE that in a real application, we would log the exception at this point
result = new Failure<T> {Exception = ex};
}
return result;
}
public void Match(Action<T> onSuccess, Action<Exception> onFailure,
Action<Exception> onBadIdea = null) {
switch (this) {
case Success<T> success:
onSuccess(success.Value);
break;
case BadIdea<T> badIdea:
if (onBadIdea != null) {
onBadIdea(badIdea.Exception);
} else {
onFailure(badIdea.Exception);
}
break;
case Failure<T> failure:
onFailure(failure.Exception);
break;
}
}
}
You then create inherited classes like this...
public abstract class Fallible<T> {
}
public class Success<T> : Fallible<T> {
public T Value { get; set; }
}
public class Failure<T> : Fallible<T> {
public Exception Exception { get; set; }
}
You can then wrap your potentially failing calls in the Do() method, and handle what happens afterwards...
var c = Fallible<Customer>.Do(() => CustomerBll.GetCustomer(id));
c.Match(
c => Customer = c,
e => AlertUser(ex)
);
The first lambda passed to Match tells it what to do in case of success, and the second tells it what to do in case of failure.
This enables you to handle your exceptions much more gracefully. See the blog post for more details.
This avoids the need for a global exception handler.

Related

How to handle or what to do if there is an Exception in Dispose() method

I have not come across any Question/Solution in Stackoverflow for this question which has got some high number of votes.
So I thought I will ask it again here.
How to handle or what to do if there is an Exception in Dispose() method.
Shall we Log it or if I Rethrow the Exception, will it get Rethrown. I might want to Rethrow it so that I come to know I made a mistake somewhere in my Dispose()
Even If we suppose it does get Rethrown, will it be a good practice to rethrow it?
In most (but not all) cases, your exception handlers should be at the code entry point.
Just let the exception bubble up, like this.
public static class Program
{
public static void Main()
{
try
{
using (new QuestionableCodeAtBest()) {}
}
catch (Exception exception)
{
Console.WriteLine(exception);
}
}
}
class QuestionableCodeAtBest : IDisposable
{
const int TotalHands = 2;
public void Dispose()
{
var handsThatAreClapping = 0;
Console.WriteLine($"What is the sound of no hands clapping?: {TotalHands / handsThatAreClapping}");
}
}

Return value to another class/object without added a relation between them C#

I having some classes related like the following domain drawing:
The Requestcontroller is running a loop in a ThreadPool, which on received messages will handle them and call some methods in FooClass, which then should throw exceptions if anything goes wrong.
In example (in some way pseudo-code):
class RequestController
{
private FooClass fooClass;
public RequestController(ref FooClass fooClass)
{
this.fooClass = fooClass;
}
void OnResponseReceived()
{
try
{
this.fooClass.ProcessingRequest("id", "requestType", 13);
}
catch(Exception ex)
{
Debug.Fail(ex.Message);
}
}
}
class FooClass
{
private object myObj;
[...]
public void ProcessingRequest(string id, string type, int count)
{
try
{
myObj.MethodAsync(id, type, RequestFailedCB, myObj);
//This method throws an Exception, that I want to be handled by RequestController class based on the Exception
}
catch(Exception)
{
throw;
}
}
}
So, my problem is that the Async method (MethodAsync in FooClass) will fail, and throw an Exception in FooClass, but it's giving me "Unhandle Exception". What I want is that the Requestcontroller is calling the method of FooClass, and if the async method that has been invoked in the FooClass.ProcessingRequest fails and throws an exception, which my RequestController should react on, and sending a message further on in the system, that there has been an error in the response received.
Would it be an idea to make the ProcessingRequest as and Callback method, or are there any better way to solve this purpose???
EDIT:
#KC-NH without posting pages of complex code, I'll try to get closer to the point.
As commented I forgot to mention that the project i .net 4 target. And the example posted in the FooClass method, is actually calling a .BeginTransfer of the UCMA 4 api, which I want to catch if it fails, and let the RequestController send a message about the failure further on in the system. The .BeginTransfer method returns IAsyncResult, and needs a Callback as one of the parameters.
The exception that the system throws, is inside this CB, but if I try to throw that exception from the Callback, I'm getting "Unhandled Exception", probably cuz the callback doesn't know where to throw that exception??
[.NET 4.5 specific solution]
You should always await async calls. await will rethrow exceptions as expected. This should correct your problem:
class RequestController
{
private FooClass fooClass;
public RequestController(ref FooClass fooClass)
{
this.fooClass = fooClass;
}
public async void OnResponseReceived()
{
try
{
await fooClass.ProcessingRequest();
}
catch (Exception ex)
{
System.Diagnostics.Debug.Fail(ex.Message);
}
}
}
public class FooClass
{
private object myObj;
public async Task ProcessingRequest()
{
await myObj.MethodAsync(id, type, RequestFailedCB, myObj);
}
}
I spoke with one of my colleagues today. He suggested that I used an EventHandler, to raise an event on exception catched in the callback method inside my FooClass. So the solution looks like this:
FooClass RequestFailedCB throws an exception
In RequestFailedCB the exception gets catched, and raising a ErrorEvent on my EventHandler.
The RequestController now gets information, that an event has been raised.
The RequestController will handle the error throw by the event, based on EventArgs and sender object, and can now send that error further on in the system.
Problem solved :) Thanks for all inputs.

C# re-throwing exception outside of scope

I am fully aware that what I am about to ask is not good practice... but:
Let's say I have a class containing a function that I want to always return a value, but store any exceptions that might occur for later processing. Something Like:
public Exception _error { get; set; }
public bool IsValid()
{
try
{
//do something here to cause exception
return true;
}
catch (Exception ex)
{
_error = ex;
return false;
}
}
Now that I have stored the exception, is it at all possible to throw the exception from an outside method while maintaining both the original stack trace and exception type?
throw _error; //lose stack trace
throw new Exception("", _error) //lose type
Thanks for looking or answering.
EDIT:
Thanks to some additional points, I realize that the below idea only takes away information and doesn't really add or simplify the situation. Thanks again to everyone.
After pondering Pieter's answer and comments, I'm now wondering if making a wrapper Exception class like the below could be a partial solution. This overrides as much of the exception as possible to make the New exception look like its innerexception, including the stacktrace.. dirty I know, but interesting:
public class ExceptionWrapper : Exception
{
private Exception _innerException;
public ExceptionWrapper(Exception ex) : base("", ex)
{
_innerException = ex;
this.Source = ex.Source;
this.HelpLink = ex.HelpLink;
}
public override string StackTrace
{
get
{
return _innerException.StackTrace;
}
}
public override System.Collections.IDictionary Data
{
get
{
return _innerException.Data;
}
}
public override string Message
{
get
{
return _innerException.Message;
}
}
public new Exception InnerException
{
get
{
return _innerException.InnerException;
}
}
}
No, this is not possible.
However, you normally solve this is by wrapping the exception in a new exception:
throw new MyException("Wrapper", _error);
This does maintain the stack trace of _error, but you do get a new exception. Your solution in your second example is the correct way of handling these cases.
Consider using reflection to create a wrapper exception of the correct type (Activator.CreateInstance) and calling the constructor that will accept the inner exception you have stored.
For example:
[Test]
public void test()
{
Exception ex = new ArgumentNullException();
Exception wrapped = (Exception)Activator.
CreateInstance(ex.GetType(), "wrapped", ex);
Type expectedType = typeof(ArgumentNullException);
Assert.IsInstanceOf(expectedType, wrapped, "Is ArgumentNullException.");
Assert.AreEqual(ex, wrapped.InnerException, "Exception is wrapped.");
}
Update
In order to mitigate the constructor issue, you could consider using the default constructor (should be there for an exception that follows design guidelines, but not mandatory) and then patching up the new instance by setting its fields via reflection.
I agree the approach is highly "meh" it's more an exploration of an idea. I wouldn't recommend it.
The exception design guidelines require a default constructor, so this sort of behaviour may go on in the framework somewhere anyway. Perhaps for some sort of icky serialization\deserialization of exceptions across some sort of communications boundary?
It seems that .net-4.5 added a new API for capturing stack/info about exceptions and rethrowing them in different contexts. This is called ExceptionDispatchInfo. It is useful if you find yourself needing more control over running tasks indirectly, like if you do manual thread management for jobs or Task does not exactly fit your needs. In your example, it should look like this:
public ExceptionDispatchInfo _error { get; private set; }
public bool IsValid()
{
try
{
//do something here to cause exception
return true;
}
catch (Exception ex)
{
_error = ExceptionDispatchInfo.Capture(ex);
return false;
}
}
/// <summary>Throw underlying exception if invalid.</summary>
public void AssertWasValid() => _error?.Throw();
Now, it doesn’t preserve the original caller. The displayed stack trace shows the calls from the original try block into the code in there, a statement breaking the original and new parts of the stack, and then the calls into ExceptionDispatchInfo.Throw() itself as the new part of the shown stack. This seems similar to how traces with async code look. If you care about the original caller, seems this won’t work. But if you care about getting the line/method that threw the exception, this should be sufficient.

What is the best way to re-use exception handling logic in C#?

I have two functions that have different enough logic but pretty much the same exception handling:
public void DoIt1 // DoIt2 has different logic but same exception handling
{
try
... DoIt1 logic
catch (MySpecialException myEx)
{
Debug.WriteLine(myEx.MyErrorString);
throw;
}
catch (Exception e)
{
Debug.WriteLine(e.ToString());
throw;
}
}
It is not possible to use a single entry point for DoIt1 and DoIt2, because they are called in from outside.
Is Copy/Pase (for the exception block) the best approach?
It depends... if there is that much commonality, you could pass in the thing to do as a parameter - either as an interface or a delegate:
void Foo(Action thingToDo) {
if(thingToDo == null) throw new ArgumentNullException("thingToDo");
try {
thingToDo();
} catch {...} // lots of
}
And call as:
Foo(delegate { /* logic A */ });
Foo(delegate { /* logic B */ });
Try:
public static class Catching<TException> where TException : Exception
{
public static bool Try<T>(Func<T> func, out T result)
{
try
{
result = func();
return true;
}
catch (TException x)
{
// log exception message (with call stacks
// and all InnerExceptions)
}
result = default(T);
return false;
}
public static T Try<T>(Func<T> func, T defaultValue)
{
T result;
if (Try(func, out result))
return result;
return defaultValue;
}
}
Example:
int queueSize = Catching<MyParsingException>
.Try(() => Parse(optionStr, "QueueSize"), 5);
If Parse throws a MyParsingException, queueSize will default to 5, otherwise the returned value from Parse is used (or any other exception will propagate normally, which is usually what you want with an unexpected exception).
This helps to avoid breaking up the flow of the code, and also centralises your logging policy.
You can write specialised versions of this kind of exception wrapping for special cases, e.g. catching a particular set of three exceptions, or whatever.
For the extreme end of the spectrum of possible solutions, check out Aspect-Oriented-Programming techniques, and tools such as PostSharp or Microsoft Policy Injection Block. This way you can define an aspect that does something on exception and weave it into all places in your code that need it.
If you just want to log the exceptions' messages and items, without doing special processing in the catch block, you could create a Reflection-based Object logger, passing the Exception as an argument. Doing so, you don't have a lot of catch blocks.
And if you are the code's owner, you can put the logging procedure inside the MySpecialException's constructor, removing the catch's block and making the code cleaner.
You could have something like:
public static class ErrorHandler
{
public static void HandleMyException(MyException myEx)
{
Debug.WriteLine(myEx.MyErrorString);
throw;
}
public static void HandleException(Exception myEx)
{
Debug.WriteLine(e.ToString());
throw;
}
}
or, in this specific case, have a more generic function like:
public static class ErrorHandler
{
public static void WriteAndThrow(string msg)
{
Debug.WriteLine(msg);
throw;
}
}

How to get the method call history?

I am trying to get the list of calls made from the beginning of a try block to the exception. In the code below, when I fall into the Catch block, the StackTrace in the Exception object is the following :
at ConsoleApplication.Program.MethodC() / at
ConsoleApplication.Program.Main(String[] args).
This is totally expected, but doesn't help me to get the history of calls. Does anybody have an idea on how I could do this?
static void MethodA() { }
static void MethodB() { }
static void MethodC() { throw new Exception(); }
static void Main(string[] args)
{
try
{
MethodA();
MethodB();
MethodC();
}
catch (Exception e)
{
// Get list of calls
throw;
}
}
I was surprised to see that the StackTrace property of the Exception object isn't StackTrace object. Is there any reason for this?
In the end, the purpose of all this is simple. If an exception is thrown during the execution of the code, I want to look at the meta data (attribute) of each of the methods called.
As I understand your question, you want to be able to know which methods was called before MethodC in your try block. I don't think you can do that without adding code to your methods.
When MethodA finishes executing, it is no longer on the stack, so there is nowhere you can get the information from. Same goes for MethodB, and only MethodC is on the stack when the Exception occurs.
It seems you're not going to be able to get a stack trace for each method called with the try block unless you add custom logging code to each method. However, you can create a System.Diagnostics.StackTrace option easily from an exception simply by passing the Exception object to the constructor. This will make available all the information about the stack trace including whether the exception was thrown from MethodA/MethodB/MethodC, which might be at least somewhat helpful to you.
Example code:
static void MethodA() { }
static void MethodB() { }
static void MethodC() { throw new Exception(); }
static void Main(string[] args)
{
try
{
MethodA();
MethodB();
MethodC();
}
catch (Exception e)
{
System.Diagnostics.StackTrace callStack = new System.Diagnostics.StackTrace(e);
System.Diagnostics.StackFrame frame = null;
System.Reflection.MethodBase calledMethod = null;
System.Reflection.ParameterInfo[] passedParams = null;
for (int x = 0; x < callStack.FrameCount; x++)
{
callStack.GetFrame(x);
calledMethod = frame.GetMethod();
passedParams = calledMethod.GetParameters();
foreach (System.Reflection.ParameterInfo param in passedParams)
System.Console.WriteLine(param.ToString());
}
}
}
(You can see this SO thread for the original answer containing the code. I've just slightly modified it.)
Hope that's at least a partial solution to your question.
You can easily get a StackTrace object from anywhere in your code but as has already been pointed out you can not get the full history of method calls.

Categories

Resources