Blog Archives

Exceptions (part 3, advanced)

For Windows Forms and WPF we have specific exceptions to deal with. Actually these are not really exceptions. They are events, which are raised whenever any unhandled exception occurs. “Unhandled” means there is nothing that catches exceptions and the entire stack did not come up with any solution. Nothing stopped the thread falling down to its lowest level, and even that level does not know what to do with the exception. You can eg. throw an exception on a button click to cause this behavior.
These events allow applications to log information about unhandled exceptions.

In Windows Forms the EventHandler is defined in System.Threading and is called ThreadExceptionEventHandler. If you do not define this event call then your application will crash when unhandled exceptions show up.

[STAThread]
static void Main() {
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.ThreadException += Application_ThreadException;
    Application.Run(new Form1());
} //

static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e) {
    Exception lException = (Exception)e.Exception;
    MessageBox.Show(lException.Message);
} //

The approach in WPF is similar. We are talking in Domains. Therefore we subscribe to AppDomain.CurrentDomain.UnhandledException .

public MainWindow() {
    InitializeComponent();
    AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;            
} //

void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) {
    Exception lException = (Exception)e.ExceptionObject;
    MessageBox.Show(lException.Message + "\nIsTerminating: " + e.IsTerminating);
} //

private void button1_Click(object sender, RoutedEventArgs e) {
    throw new Exception("user exception thrown");
} //
Advertisements

Exceptions (part 2, advanced)

Season’s Greetings!
Today we have a very short post about custom exceptions, which provide more specific information. Of course the custom exception has to inherit from System.Exception. Adding several constructors including a parameterless one is good practice.
The suffix “Exception” in your exception name is convention (eg. “OutOfMemory
Exception
“, “FileNotFoundException“). Adding the Serializable attribute can be useful when you work across application domains. Properties help providing extra information.

Don’t use the System.ApplicationException class.
http://msdn.microsoft.com/en-us/library/system.applicationexception.aspx states:

If you are designing an application that needs to create its own exceptions, you should derive custom exceptions from the Exception class. It was originally thought that custom exceptions should derive from the ApplicationException class; however in practice this has not been found to add significant value.

In other words: ApplicationException is a relic of the past, where Microsoft intended developers to inherit all their custom exceptions from. But this has never become practice and custom exceptions now derive from the Exception class.

[Serializable]
public class UserNotFoundException : Exception {
    public string UserId { get; private set; }
            
    public UserNotFoundException(string xUserId) : base() {
        UserId = xUserId;
        base.HelpLink = "http://www.ohta.de";
    } // constructor

    public UserNotFoundException(string xUserId, string xMessage)
        : base(xMessage) {
        UserId = xUserId;
        base.HelpLink = "http://www.ohta.de";
    } // constructor

    public UserNotFoundException(string xUserId, string xMessage, Exception xInnerException)
        : base(xMessage, xInnerException) {
        UserId = xUserId;
        base.HelpLink = "http://www.ohta.de";
    } // constructor

    protected UserNotFoundException(SerializationInfo xSerializationInfo, StreamingContext xStreamingContext) {
        UserId = xSerializationInfo.GetValue("UserId", typeof(string)) as string;
    } // constructor

    public void GetObjectData(SerializationInfo xSerializationInfo, StreamingContext xStreamingContext) {
        xSerializationInfo.AddValue("UserId", UserId, typeof(string));
    }
} // class

Exceptions (part 1, advanced)

Exceptions are not errors, they are exceptions. They should not be used for code that can deal with errors. Exceptions are for situations that cannot be solved like running out of RAM or hard disk space. They are pretty slow, because they deal with the entire stack trace. Here is a short benchmark program:

static double DoSomeCalc(double d) {
    return d * 1.1;
} //
static double DoSomeCalc2(Exception e) {
    throw e;
} //

static void Exceptions1() {
    const int n = 10000000;
    double d = 1.0;

    Stopwatch lStopwatch = new Stopwatch();
    lStopwatch.Start();

    for (int i = 0; i < n; i++) d *= 1.1;
    Console.WriteLine("benchmark ms " + lStopwatch.ElapsedMilliseconds);

    lStopwatch.Restart();
    try { for (int i = 0; i < n; i++)  d *= 1.1; }
    catch (Exception) { throw; }
    Console.WriteLine("efficient try/catch block ms " + lStopwatch.ElapsedMilliseconds);

    lStopwatch.Restart();
    for (int i = 0; i < n; i++) {
        try { d *= 1.1; }
        catch (Exception) { throw; }
    }
    Console.WriteLine("inefficient try/catch block ms " + lStopwatch.ElapsedMilliseconds);
    Console.WriteLine();

    lStopwatch.Restart();
    for (int i = 0; i < n; i++) d = DoSomeCalc(d);
    Console.WriteLine("method call, benchmark ms " + lStopwatch.ElapsedMilliseconds);

    lStopwatch.Restart();
    try { for (int i = 0; i < n; i++)  d = DoSomeCalc(d); }
    catch (Exception) { throw; }
    Console.WriteLine("method call, efficient try/catch block ms " + lStopwatch.ElapsedMilliseconds);

    lStopwatch.Restart();
    for (int i = 0; i < n; i++) {
        try { d = DoSomeCalc(d); }
        catch (Exception) { throw; }
    }
    Console.WriteLine("method call, inefficient try/catch block ms " + lStopwatch.ElapsedMilliseconds);
    Console.WriteLine();

    Exception e = new Exception();  // only one instance, we exclude the creation time for the object in this test
    lStopwatch.Restart();
    for (int i = 0; i < 100; i++) {
        try { throw e; }
        catch (Exception) { }
    }
    Console.WriteLine("100 exceptions thrown in ms " + lStopwatch.ElapsedMilliseconds);

    lStopwatch.Restart();
    for (int i = 0; i < 100; i++) {
        try { DoSomeCalc2(e); }
        catch (Exception) { }
    }
    Console.WriteLine("method call, 100 exceptions thrown in ms " + lStopwatch.ElapsedMilliseconds);

    lStopwatch.Stop();
    Console.ReadLine();
} //

example output:
benchmark ms 2227
efficient try/catch block ms 2179
inefficient try/catch block ms 2201

method call, benchmark ms 2448
method call, efficient try/catch block ms 2436
method call, inefficient try/catch block ms 2431

100 exceptions thrown in ms 603
method call, 100 exceptions thrown in ms 652

The first three results are in line with each other. The code optimizer does the job and there is no visible impact on the outcome. The difference is more likely to be a result of context switching (threading).
And when we call a method the slowdown is also regular, no big impact of the try/catch blog.
But when exceptions are thrown, the system considerably slows down. 600 ms for just 100 exceptions is a disaster. And it gets even worse when you call a method, because the stack trace becomes longer. Imagine what happens when you have nested methods involved.

The conclusion is that throwing exceptions for the programmer’s convenience is bad practice. Exceptions must be avoided by all means. You’d rather perform a quick zero check than raise a DivideByZeroException.

Do not reuse exception objects, this is not thread safe. In general try to avoid re-throwing exceptions. Anyway, let’s see how to re-throw exceptions in case you need it:

a) Re-“throw” without any identifier. This preserves the original exception details.

static void Exceptions2() {
    int lZero = 0;
    try { int i = 4 / lZero; }
    catch (Exception) { throw; }
} //

static void Exceptions3() {
    try { Exceptions2(); }
    catch (Exception e) {
        Console.WriteLine("Message:        {0}", e.Message);
        Console.WriteLine("StackTrace:     {0}", e.StackTrace);
        Console.WriteLine("HelpLink:       {0}", e.HelpLink);
        Console.WriteLine("InnerException: {0}", e.InnerException);
        Console.WriteLine("TargetSite:     {0}", e.TargetSite);
        Console.WriteLine("Source:         {0}", e.Source);
    }
} //

Message: Attempted to divide by zero.
StackTrace: at ConsoleApplication1.Program.Exceptions2() in ….\Program.cs:line 1155
at ConsoleApplication1.Program.Exceptions3() in ….\Program.cs:line 1160
HelpLink:
InnerException:
TargetSite: Void Exceptions2()
Source: ConsoleApplication1

b) Re-throw the original exception. Add some more information.

static void Exceptions4() {
    int lZero = 0;
    try { int i = 4 / lZero; }
    catch (DivideByZeroException e) { throw new DivideByZeroException("Division by Zero", e); }
    catch (Exception e) { throw new Exception("Any Exception", e); } // will not be thrown in this example
} //

static void Exceptions5() {
    try { Exceptions4(); }
    catch (Exception e) {
        Console.WriteLine("Message:        {0}", e.Message);
        Console.WriteLine("StackTrace:     {0}", e.StackTrace);
        Console.WriteLine("HelpLink:       {0}", e.HelpLink);
        Console.WriteLine("InnerException: {0}", e.InnerException);
        Console.WriteLine("TargetSite:     {0}", e.TargetSite);
        Console.WriteLine("Source:         {0}", e.Source);
    }
} //

example output:
Message: Division by Zero
StackTrace: at ConsoleApplication1.Program.Exceptions4() in ….\Program.cs:line 1134
at ConsoleApplication1.Program.Exceptions5() in ….\Program.cs:line 1140
HelpLink:
InnerException: System.DivideByZeroException: Attempted to divide by zero.
at ConsoleApplication1.Program.Exceptions4() in ….\Program.cs:line 1133
TargetSite: Void Exceptions4()
Source: ConsoleApplication1

Events (part 3, advanced)

Events: Let’s go multithreading! We want the crème de la crème. Well, multitasking is also fine.

The code does not need to run in a specific sequence. The required independence is given. Again, there are many ways to use multithreading. An easy approach is to start a task in each method that is called by the event.

C# does support BeginInvoke() for delegates. This method is not supported by the .NET Compact Framework though. We don’t care, because our hardcore programs are for serious applications, definitely not for mobile phone apps. Let’s see how good BeginInvoke() works. Maybe we don’t have to reinvent the wheel.

BeginInvoke() initiates asynchronous calls, it returns immediately and provides the IAsyncResult, which can be used to monitor the progress of the asynchronous call.
EndInvoke() retrieves the results. It blocks until the thread has completed.

You have the following options after calling BeginInvoke():
1) Call EndInvoke() to block the current thread until the call completes.
2) Obtain the WaitHandle from IAsyncResult.AsyncWaitHandle, use its WaitOne() and then call EndInvoke().
3) Poll the IAsyncResult to check the current state, after it has completed call EndInvoke().
4) Pass a callback to BeginInvoke(). The callback will use the ThreadPool to notify you. In the callback you have to call EndInvoke().

public event EventHandler OnChange;

public void DoSomeWork(object sender, object e) {
    Thread.Sleep(2100);
    Console.WriteLine("Thread " + Thread.CurrentThread.ManagedThreadId + " mission accomplished!");
} //

public void RunMyExample() {
    OnChange += new EventHandler(DoSomeWork);
    //OnChange += new EventHandler(DoSomeWork);
    //OnChange += new EventHandler(DoSomeWork);

    IAsyncResult lAsyncResult;

    Console.WriteLine("Choice 1");
    lAsyncResult = OnChange.BeginInvoke(this, EventArgs.Empty, null, null);
    OnChange.EndInvoke(lAsyncResult);

    Console.WriteLine("Choice 2");
    lAsyncResult = OnChange.BeginInvoke(this, EventArgs.Empty, null, null);
    lAsyncResult.AsyncWaitHandle.WaitOne();

    Console.WriteLine("Choice 3");
    lAsyncResult = OnChange.BeginInvoke(this, EventArgs.Empty, null, null);
    while (!lAsyncResult.IsCompleted) {
        Thread.Sleep(500);
        Console.WriteLine("work still not completed :(");
    }

    Console.WriteLine("Choice 4"); 
    OnChange.BeginInvoke(this, EventArgs.Empty, (xAsyncResult) => {
            Console.WriteLine("callback running");
            OnChange.EndInvoke(xAsyncResult);
        }, null);

    Console.WriteLine("press return to exit the program");
    Console.ReadLine();
}//    

example output:
Choice 1
Thread 6 mission accomplished!
Choice 2
Thread 6 mission accomplished!
work still not completed 😦
work still not completed 😦
work still not completed 😦
work still not completed 😦
Thread 10 mission accomplished!
work still not completed 😦
press return to exit the program
Thread 6 mission accomplished!
callback running

After having lived such a nice life, we have to face a major issue with BeginInvoke(). Uncomment “//OnChange += new EventHandler(DoSomeWork);”, don’t get annoyed now!
You will get an error message saying

“The delegate must have only one target”.

Although the delegate class can deal with multiple targets, asynchronous calls accept just one target.

So let’s try something else.

    public event EventHandler OnChange;

    public void DoSomeWork(object sender, object e) {
        Thread.Sleep(2100);
        Console.WriteLine("Thread " + Thread.CurrentThread.ManagedThreadId + " mission accomplished!");
    } //

    public void RunMyExample() {
        OnChange += new EventHandler(DoSomeWork);
        OnChange += new EventHandler((sender, e) => { throw new Exception("something went wrong"); });
        OnChange += new EventHandler(DoSomeWork);

        EventHandler lOnChange = OnChange;
        if (lOnChange == null) return;   // just to demonstrate the proper way to call events, not needed in this example                
        foreach (EventHandler d in lOnChange.GetInvocationList()) {
            Task lTask = Task.Factory.StartNew(() => d(this, EventArgs.Empty));
            lTask.ContinueWith((i) => { Console.WriteLine("Task canceled"); }, TaskContinuationOptions.OnlyOnCanceled);
            lTask.ContinueWith((i) => { Console.WriteLine("Task faulted"); }, TaskContinuationOptions.OnlyOnFaulted);
            lTask.ContinueWith((i) => { Console.WriteLine("Task completion"); }, TaskContinuationOptions.OnlyOnRanToCompletion);
        }

        Console.WriteLine("press return to exit the program");
        Console.ReadLine();
    }//    

It seems that Microsoft has a serious bug here.This code does not execute properly each time. I guess it has to do with the asynchronous behaviour of StartNew(). It sometimes calls the wrong method DoSomeWork() three times and does not raise the exception.
It seems foreach overrides variable “d” before it is inserted in StartNew(). With a little tweak we can avoid this bug. We simply assign “d” to a new local variable. That way we have unique copies of “d”. Weird stuff, but that is the life of a coder sometimes.

public event EventHandler OnChange;

public void DoSomeWork(object sender, object e) {
    Thread.Sleep(2100);
    Console.WriteLine("Thread " + Thread.CurrentThread.ManagedThreadId + " mission accomplished!");
} //

public void RunMyExample() {
    OnChange += new EventHandler(DoSomeWork);
    OnChange += new EventHandler((sender, e) => { throw new Exception("something went wrong"); });
    OnChange += new EventHandler(DoSomeWork);

    EventHandler lOnChange = OnChange;
    if (lOnChange == null) return;   // just to demonstrate the proper way to call events, not needed in this example                
    foreach (EventHandler d in lOnChange.GetInvocationList()) {
        EventHandler e = d;
        Task lTask = Task.Factory.StartNew(() => e(this, EventArgs.Empty));
        lTask.ContinueWith((i) => { Console.WriteLine("Task canceled"); }, TaskContinuationOptions.OnlyOnCanceled);
        lTask.ContinueWith((i) => { Console.WriteLine("Task faulted"); }, TaskContinuationOptions.OnlyOnFaulted);
        lTask.ContinueWith((i) => { Console.WriteLine("Task completion"); }, TaskContinuationOptions.OnlyOnRanToCompletion);
    }

    Console.WriteLine("press return to exit the program");
    Console.ReadLine();
}//    

Example output:
press return to exit the program
Thread 11 mission accomplished!
Thread 10 mission accomplished!
Task completion
Task faulted
Task completion

This tiny tweak worked. You just have to know the compiler bugs. I hope this little notice saves you at least 3 hours of work.
You probably remember that we faced a similar issue in my post “Exiting Tasks (advanced)” https://csharphardcoreprogramming.wordpress.com/2013/12/11/exiting-tasks/ . I would suggest to only use Task.Factory.StartNew() with caution. Maybe it only happens in conjunction with lambda expressions.
The following code is also running very well. The variable “d” is not used directly in Task.Factory.StartNew().

...
 foreach (EventHandler d in lOnChange.GetInvocationList()) {
            Action a = () => d(this, EventArgs.Empty);
            Task lTask = Task.Factory.StartNew(a);
            lTask.ContinueWith((i) => { Console.WriteLine("Task canceled"); }, TaskContinuationOptions.OnlyOnCanceled);
            lTask.ContinueWith((i) => { Console.WriteLine("Task faulted"); }, TaskContinuationOptions.OnlyOnFaulted);
            lTask.ContinueWith((i) => { Console.WriteLine("Task completion"); }, TaskContinuationOptions.OnlyOnRanToCompletion);
        }
...

Events (part 2, advanced)

We are going to construct our custom event accessor now. It deals with additions and removals of subscriptions. Accessors do pretty much look like property definitions. But instead of set and get you have to use add and remove.

public class MyActionEvent4 {
    private object _Lock = new object();            // a new object simply to avoid lock conflicts
    private event EventHandler<MyArgs> _OnChange;
    private event EventHandler<MyArgs> OnChange {
        add {
            lock (_Lock) { _OnChange += value; }
        }
        remove {
            lock (_Lock) { _OnChange -= value; }
        }
    } //

    public void RaiseEvent() {
        lock (_Lock) {
            EventHandler<MyArgs> lHandler = _OnChange;
            if (lHandler == null) return;
            lHandler(this, new MyArgs(0));   
        }        
    }//
} // class

Now we have one big problem here. The RaiseEvent() method has to obtain a lock each time, which causes a serious impact on time sensitive programs. Luckily you do not need to care about changing subscriptions during the invocation. Delegate references are thread-safe, because they are immutable like strings. Let’s simply take the lock out of the RaiseEvent() method, et voilà!

public class MyActionEvent5 {
    private object _Lock = new object();
    private event EventHandler<MyArgs> _OnChange;
    private event EventHandler<MyArgs> OnChange {
        add {
            lock (_Lock) { _OnChange += value; }
        }
        remove {
            lock (_Lock) { _OnChange -= value; }
        }
    } //

    public void RaiseEvent() {
        EventHandler<MyArgs> lHandler = _OnChange;
        if (lHandler == null) return;
        lHandler(this, new MyArgs(0));   
    }//
} // class

It is clear that events are not delegates. They restrict access rights from outside of the event class. To describe events you could most likely say that they are wrappers around delegates.

Whenever an exception is thrown during an event call then all following calls will not be executed. And it is tricky to determine which calls were not executed, because the order of event calls is not guaranteed to be in sequence. In fact it does execute in sequence, but there is no guarantee.

static void EventExceptions1() {
    MyActionEvent3 lEvent = new MyActionEvent3();
    lEvent.OnChange += (sender, e) => Console.WriteLine("Executed subscription 1");
    lEvent.OnChange += (sender, e) => { throw new Exception("OMG!"); };
    lEvent.OnChange += (sender, e) => Console.WriteLine("Executed subscription 3");
    lEvent.RaiseEvent();
} //

So you have to deal with exceptions manually if you want to satisfy/execute as many event subscriptions as possible. You could add a try/catch block for each subscription. Or you could invoke the InvocationList yourself by calling the GetInvocationList() method [System.Delegate] and execute each item manually in a try/catch block. Let’s have a look at the following practical solution:

public class MyActionEvent6 {
    public event EventHandler OnChange = delegate { };

    public void RaiseEvent() {
        List<Exception> lExceptions = new List<Exception>();

        foreach (Delegate lHandler in OnChange.GetInvocationList()) {
            try { lHandler.DynamicInvoke(this, EventArgs.Empty); }
            catch (Exception ex) { lExceptions.Add(ex); }
        }

        if (lExceptions.Count > 0) throw new AggregateException(lExceptions);
    }//
} // class

static void EventExceptions6() {
    MyActionEvent6 lEvent = new MyActionEvent6();
    lEvent.OnChange += (sender, e) => Console.WriteLine("Executed subscription 1");
    lEvent.OnChange += (sender, e) => { throw new Exception("OMG!"); };
    lEvent.OnChange += (sender, e) => Console.WriteLine("Executed subscription 3");

    try { lEvent.RaiseEvent(); }
    catch (AggregateException ex) {
        foreach (Exception lException in ex.InnerExceptions) {
            Console.WriteLine(lException.InnerException.Message);
        }
    }
} //