Question

Can please someone explain, in a very easy/simple way, how to handle an exception via attributes?

For example if I have simple code like this:

class Test{
static void Main(string[] args){
    try {
            Console.WriteLine("div= "+ Division(0));
        }
        catch (DivideByZeroException e)
        {
            Console.WriteLine("Attempted divide by zero -->" + e.Message);
        }

        Console.ReadLine();   
    }

    public static int Division(int i){  return 10 / i; }
}

How can I change this code using attributes?

Was it helpful?

Solution

This cannot be done with .NET out of the box.

tl;dr - There is no "very easy/simple way (...) to handle an exception via attributes"


You're trying to handle exceptions in a AOP way (aspect oriented programming), where you attach aspects to methods - using attributes, for example.

PostSharp allows you to do this:

Without postsharp:

public class OrderFulfillmentService  
{ 
    public void Fulfill( Order order )  
    { 
       try  
       { 
          // Do stuff.   
       }  
       catch ( Exception e ) 
       { 
            if ( ExceptionHandler.Handle(e) ) 
                throw; 
       }  
    }  
} 

With postsharp:

public class OrderFulfillmentService  
{ 
    [HandleException]  
    public void Fulfill( Order order )  
    { 
        // Do stuff. 
    } 
}

Beware of the downsides of using AOP though: the code might become less readable (as it isn't written sequentially) and less maintainable.


Instead of using attributes, you could also use Castle Interceptor/DynamicProxy

You will need to create an interceptor that wraps around your object and intercepts calls to it. At runtime, Castle will make this interceptor either extend your concrete class or implement a common interface - this means you'll be able to inject the interceptor into any piece of code that targets the intercepted class. Your code would look something like this:

public class Interceptor : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
       try{
            invocation.Proceed();
        } catch(Exception ex) {
           //add your "post execution" calls on the invocation's target
        }
    }
}

Introduction to AOP with Castle: http://docs.castleproject.org/Windsor.Introduction-to-AOP-With-Castle.ashx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top