One Exception handler for all exceptions of a CLASS

前端 未结 6 1644
甜味超标
甜味超标 2021-02-04 01:05

I have a class with number of methods and want to have one exception handler for them all. There are so many of these methods and they have different parameters, that it would b

6条回答
  •  无人共我
    2021-02-04 01:39

    You could use a delegate to pass your method's code into a single try catch like the following example:

        private void GlobalTryCatch(Action action)
        {
            try
            {
                action.Invoke();
            }
            catch (ExpectedException1 e)
            {
                throw MyCustomException("Something bad happened", e);
            }
            catch (ExpectedException2 e)
            {
                throw MyCustomException("Something really bad happened", e);
            }
        }
    
        public void DoSomething()
        {
            GlobalTryCatch(() =>
            {
                // Method code goes here
            });
        }
    

提交回复
热议问题