Catching Unhandled Exceptions in .NET

I’m currently working on a Rhino plugin in C# / .NET / WPF using the RhinoCommon SDK.

Is there a way to catch unhandled exceptions that occur within my plugin?

I’ve tried subscribing to the following events, without luck:
AppDomain.CurrentDomain.UnhandledException
Dispatcher.CurrentDispatcher.UnhandledException

If I throw an unhandled Exception, instead of going through my exception handler, I end up in an endless retry-loop for some odd reason. Is that by design?

Is there some built-in functionality in the RhinoCommon SDK that I’m missing that can help with this?

I’m well aware of the general try-catch syntax :slight_smile:
I’m referring to unhandled exceptions, or unexpected if you will, that you typically handle in normal WPF applications by subscribing to the aforementioned events.

1 Like

Hi @grenadilla ,
Subscribing to AppDomain.CurrentDomain.UnhandledException is a way to do it. How are you handling it? Do you have a sample?

Hi @Darryl_Menezes.
Thanks for the response.

Here is how I’ve implemented the error handling:

1. Subscribe to the UnhandledException event:

public class MyPlugIn : Rhino.PlugIns.PlugIn
{
    ...	
    protected override LoadReturnCode OnLoad(ref string errorMessage)
	{
	    AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionHandler);
        ...
	}

	static void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs args)
	{
	    //Never get to here!
	    Exception e = (Exception)args.ExceptionObject;
        ...
	}
}

2. Throw an unhandled exception within a command

public class MyRhinoCommand : Command
{	
	...
	protected override Result RunCommand(RhinoDoc doc, RunMode mode)
    {
        throw new Exception("Unhandled Test");
        ...
	}
}

All RunCommand functions are wrapped in a try/catch block by Rhino itself.

1 Like

As @stevebaer says, Rhino is swallowing your exceptions in their own try/catch. You can however wrap your logic in each RunCommand() call, in your own try/catch if you are actually trying to handle the exception and perform necessary logic or logging.

image