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

2

6

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.

Cressy answered 11/5, 2012 at 14:14 Comment(1)
Um, your method is decorated with [OnExceptionAspect] so it will do the default PostSharp OnExceptionAspect behaviour which is nothing. You need to decorate it with [ExceptionAspectHandler] to get your code to workBatchelder
I
5

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.

Ingate answered 11/5, 2012 at 14:33 Comment(1)
From this blog post, it looks like the exception is automatically rethrown. If you set the FlowBeheavor to Continue, the exception is not rethrown. I think that is the opposite of what's said in this answer.Jarmon
H
0

The attribute used in divide() method should be ExceptionAspectHandler (you've created), not OnExceptionAspect.

Hanford answered 15/2, 2013 at 17:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.