One Exception handler for all exceptions of a CLASS

前端 未结 6 1691
甜味超标
甜味超标 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:45

    I don't think there is. You could move the try/catch to the caller, but that's not very good design. It may be better to separate it out into another class, and use Reflection to call the methods, like this:

    public class MyClass {}
    public class MySafeClass {
        public void CallMethod(string name, object[] param) {
            Type t = typeof(MyClass);
            MyClass mc = new MyClass();
            try {
                t.GetMethod(name).Invoke(mc, param);
            }
            catch {
                //...;
            }
        }
    

    }

    But you shouldn't! It's not very good practice.

    Another method is still using try/catch but having a single method to throw exceptions, etc back to the user:

    public class MyClass {
        void DoException(string message) {
            throw new Exception(message);
        }
    }
    

    But that still isn't that good an option.

    I don't see why it would be ugly - even if you just wrap the whole method in one try/catch with a message. That might be feasible.

    It's also a better option to just leave them and pass them back up to the caller, perhaps in try/finally.

    It's not exactly hard to try/catch everything, especially with the snippets in Visual Studio and SharpDevelop.

提交回复
热议问题