如何使用OnException方面(PostSharp)继续方法流?

Gus*_*uma 6 c# aop exception-handling postsharp visual-studio

我有以下代码:

[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");
            }
Run Code Online (Sandbox Code Playgroud)

使用FlowBehavior.Continue结束divide()并返回main()方法.

Dus*_*vis 5

请记住,OnException方面将您的代码包装在try / catch中,因此代码将从catch继续(而不是重新抛出),并且其行为将默认返回。您是否希望它从引发异常的地方继续?如果是这样,则需要自己明确地将该行包装在try / catch中。

请阅读http://www.sharpcrafters.com/blog/post/Day-6-Your-code-after-PostSharp.aspx了解更多详细信息。