Why is it better to throw an exception rather than return an error code?

前端 未结 4 870
小蘑菇
小蘑菇 2021-01-31 08:44

Legacy error handling tends to follow the method that all functions return a code depending on success/failure. You would check this code and handle (if an error) appropriately

4条回答
  •  無奈伤痛
    2021-01-31 09:09

    I've written about this at length: Exceptions vs. status returns, but briefly:

    1. Exceptions leaves your code clean of all the checks necessary when testing status returns on every call,
    2. Exceptions let you use the return value of functions for actual values,
    3. Exceptions can carry more information than a status return can,
    4. Most importantly: exceptions can't be ignored through inaction, while status returns can.

    To expand on the last point: if you forget to do what you should be doing with status returns, you ignore errors. If you forget to do what you should be doing with exceptions, the exception bubbles up to the outer layer of the software where it becomes visible.

提交回复
热议问题