为什么抛出异常而不是返回错误代码呢

为什么抛出异常而不是返回错误代码呢

本文介绍了为什么抛出异常而不是返回错误代码呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

传统的错误处理往往遵循所有函数根据成功/失败返回代码的方法。您将检查此代码并正确处理(如果出现错误)。



现代编程语言遵循异常模式,如果发生异常发生我们的问题是为什么我们转向异常模型?



>?这背后的原因是什么?为什么会更好?



解释/链接将不胜感激。

解决方案

我已经详细说明了这一点: ,但简要地:


  1. 例外情况是,每次呼叫测试状态返回时,您的代码将清除所有必需的检查,

  2. 例外可以使用函数的实际值的返回值,

  3. 异常可以携带比状态返回更多的信息,

  4. 最重要的是:异常不能通过不作为忽略,而状态返回可以。

展开最后一点:如果你忘记做你应该做的状态返回,你忽略错误。如果你忘记做了你应该做的例外,那么这个例外就会发生在软件外层可见的空白。


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.

Modern programming languages however follow the exception model, where if something exceptional happens that cannot be handled properly an exception gets thrown - which keeps bubbling up until its handled.

My question is why have we moved towards the exception model? What are the reasons behind this? Why is it better?

Explanations/links would be much appreciated.

解决方案

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.

这篇关于为什么抛出异常而不是返回错误代码呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 19:29