Determine if executing in finally block due to exception being thrown

前端 未结 8 1262
遥遥无期
遥遥无期 2020-12-16 10:01

Is it possible to determine if code is currently executing in the context of a finally handler as a result of an exception being thrown? I\'m rather fond of usi

8条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-16 10:26

    The following pattern avoids the problem with API misuse i.e. a scope completion method not being called i.e. omitted completely, or not being called because of a logical condition. I think this answers your question more closely and is even less code for the API user.

    Edit

    Even more straightforward after Dan's comment:

    public class Bling
    {
        public static void DoBling()
        {
            MyScopedBehavior.Begin(() =>
            {
                //Do something.
            }) ;
        }   
    }
    
    public static class MyScopedBehavior
    {
        public static void Begin(Action action)
        {
            try
            {
                action();
    
                //Do additonal scoped stuff as there is no exception.
            }
            catch (Exception ex)
            {
                //Clean up...
                throw;
            }
        }
    }   
    

提交回复
热议问题