Why is exception handling bad?

前端 未结 15 1405
温柔的废话
温柔的废话 2020-12-04 05:46

Google\'s Go language has no exceptions as a design choice, and Linus of Linux fame has called exceptions crap. Why?

15条回答
  •  感情败类
    2020-12-04 06:08

    I disagree with "only throw exceptions in an exceptional situation." While generally true, it's misleading. Exceptions are for error conditions (execution failures).

    Regardless of the language you use, pick up a copy of Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries (2nd Edition). The chapter on exception throwing is without peer. Some quotes from the first edition (the 2nd's at my work):

    • DO NOT return error codes.
    • Error codes can be easily ignored, and often are.
    • Exceptions are the primary means of reporting errors in frameworks.
    • A good rule of thumb is that if a method does not do what its name suggests, it should be considered a method-level failure, resulting in an exception.
    • DO NOT use exceptions for the normal flow of control, if possible.

    There are pages of notes on the benefits of exceptions (API consistency, choice of location of error handling code, improved robustness, etc.) There's a section on performance that includes several patterns (Tester-Doer, Try-Parse).

    Exceptions and exception handling are not bad. Like any other feature, they can be misused.

提交回复
热议问题