How to throw good exceptions?

前端 未结 12 1358
情话喂你
情话喂你 2020-12-14 21:05

I heard you should never throw a string because there is a lack of information and you\'ll catch exceptions you dont expect to catch. What are good practice for throwing exc

12条回答
  •  一生所求
    2020-12-14 21:44

    One basic thing is to reserve exceptions for exceptional situations only. Don't use them for flow control. For instance, "file not found" should not be an exception, it should be an error code or return value (unless the file is something that must exist, e.g. a configuration file). But if a file suddenly disappears while you're processing it, then throwing an exception is a good choice.

    When exceptions are used sparingly, you don't need to turn your code into a try-catch -spaghetti in order to avoid receiving incomprehensible-in-the-context exceptions from the deeper layers.

提交回复
热议问题