Should event handlers in C# ever raise exceptions?

前端 未结 5 739
攒了一身酷
攒了一身酷 2020-12-14 14:59

As a general rule, are there ever any circumstances in which it\'s acceptable for a method responsible for listening to an event to throw an exception (or allow to be thrown

5条回答
  •  盖世英雄少女心
    2020-12-14 15:13

    The only two types of exceptions that should come out of events are serious, potentially process-ending ones like System.OutOfMemoryException or System.DllNotFoundException, and things that are clearly programming errors, like System.StackOverflowException or System.InvalidCastException. Catching and dropping these kinds of exceptions is never a good idea -- let them float up to the top and let the developer decide what to do with them on an application level.

    As for the rest... any common or garden-variety exception like System.IO.IOException should be handled inside your event, and you should have some mechanism for returning such error conditions to the caller.

提交回复
热议问题