Setting the message of a custom Exception without passing it to the base constructor

后端 未结 5 1295
悲&欢浪女
悲&欢浪女 2021-02-11 12:20

I want to make a custom Exception in C#, but in theory I do need to do a little parsing first before I can make a human readable ExceptionMessage.

The problem is that th

5条回答
  •  旧时难觅i
    2021-02-11 12:31

    I think the problem may be with the Visual Studio debugger. I got the same exact results you got using the debugger, but when I print the message instead:

    class CustomException : Exception {
        public CustomException(dynamic json)
            : base("Plep") {
                _Message = json.message;
        }
    
        public override string Message {
            get { return _Message; }
        }
    
        private string _Message;
    }
    
    class Program {
        static void Main(string[] args) {
            try {
                throw new CustomException(new { message = "Show this message" });
            } catch (Exception ex) {
                Console.WriteLine(ex.Message);
            }
        }
    }
    

    I get the expected "Show this message".

    If you put a breakpoint where the Exception is caught, the debugger does show you the correct message.

提交回复
热议问题