Search code examples
c#visual-studioexceptionaoppostsharp

How to continue method flow using OnException aspect (PostSharp)?


I have the following code:

[Serializable]
    class ExceptionAspectHandler:OnExceptionAspect
    {
        public override void OnException(MethodExecutionArgs args)
        {
            Console.WriteLine("{0}", args.Exception);
            args.FlowBehavior = FlowBehavior.Continue;
        }
    }

    [OnExceptionAspect]
    public static void divide()
            {
                int n = Convert.ToInt32(Console.ReadLine());
                var a = 100 / n; //the exception happens here
                Console.WriteLine("it should get here");
            }

Using FlowBehavior.Continue ends divide() and returns to the main() method.


Solution

  • Remember, the OnException aspect wraps your code in a try/catch so the code will continue from the catch (instead of rethrowing) and it's behavior will default to return. Are you wanting it to continue from where it threw the exception? If so, you need to explicitly wrap that line in a try/catch yourself.

    Please read http://www.sharpcrafters.com/blog/post/Day-6-Your-code-after-PostSharp.aspx for more details.