Would you ever NOT catch an exception, or throw an exception that won't be caught?

前端 未结 14 986
感情败类
感情败类 2021-01-03 09:49

I\'ve dealt with instances where I would throw/rethrow an exception knowing that the code surrounding it would catch the specific exception. But is there any time you would

14条回答
  •  旧巷少年郎
    2021-01-03 10:08

    There's a very good rule that I came across a while ago:

    Throw an exception when a method can't do what its name says it does.

    The idea is that an exception indicates that something has gone wrong. When you are implementing a method, it is not your responsibility to be aware of whether it will be used correctly or not. Whether the code using your method catches the exception or not is not your responsibility, but the responsibility of the person using your method.

    Another rule to follow is:

    Don't catch an exception unless you know what you want to do with it.

    Obviously, you should include cleanup code in a try...finally block, but you should never just catch an exception just for the sake of catching it. And you should never swallow exceptions silently. While there are occasions when you may want to catch all exceptions (e.g. by doing catch (Exception ex) in C#), these are fairly uncommon and generally have a very specific technical reason. For example, when you are using threads in .NET 2.0 or later, if an exception escapes from your thread, it will cause the entire application domain to unload. In these cases, however, at the very minimum you should log the exception details as an error and provide an explanation in the comments.

提交回复
热议问题