Exception handling

With exception handling in Catel, it is possible to create an exception handling policy and execute code in a safe way without have to check all the exception types manually. Catel exposes this technique via the IExceptionService.

Setting up the IExceptionService

It is important to register an exception in the service and let Catel know how it should be handled. The service handles exceptions in the way they are added to the IExceptionService.

 The example below registers several exceptions and how they should be handled. When a FileNotFoundException occurs, it will show a message to the user. For any other exception, it will log the exception and show a message that the user should contact the developers.

var exceptionService = GetService<IExceptionService>();

exceptionService.Register<FileNotFoundException>(exception => GetService<IMessageService>().Show(exception.Message));
exceptionService.Register<Exception>(exception => {
Log.Error(exception);
GetService<IMessageService>().Show("An unknown exception occurred, please contact the developers"); 
});

The IExceptionService checks for type hierarchy. For example, when an exception as type Exception is registered, this handler will handle all exceptions

Executing code using the IExceptionService

The Process method is responsible to keep track of all exceptions which might occur and will handle them if they are registered. If one of your registered exceptions is thrown by the code, the Process method will handle it and perform the action defined while the registration operation (for example, by showing a message box).

The Process method comes in two flavors: as action and as function.

Executing an action

var exceptionService = GetService<IExceptionService>();
exceptionService.Process(() => { throw new ArgumentOutOfRangeException(); });

Executing a function

var exceptionService = GetService<IExceptionService>();
var result = exceptionService.Process<int>(() => 1 + 1);

Handling exceptions manually

 It is possible to manually handle exceptions using the service. This is useful when you don't want to wrap code in the Process method, but still want to be able to create a generic exception handling policy.

var exceptionService = GetService<IExceptionService>();

try
{
    var value = 150/0;
}
catch (DivideByZeroException exception)
{
    exceptionService.HandleException(exception);
}

If the exception can be handled, the registered action will be executed, but your code can safely continue. If the exception (in this case DivideByZeroException) is not registered, the HandleException method will rethrow the exception.

 Unregistering exceptions

Although it will probably hardly used, it is possible to unregister exceptions again using the code below:

var exceptionService = GetService<IExceptionService>();
exceptionService.Unregister<ArgumentException>();