异常可以用if..else完美替代吗?

发布于 2024-11-29 11:42:25 字数 214 浏览 1 评论 0原文

我是编程新手,有一个概念性问题。

也就是说,“异常”可以完美地用“if..else”代替吗?

我知道“异常”是处理一些可能导致错误或崩溃的异常情况。

但我们也用“if..else”来保证变量值的正确性,不是吗?

或者“异常”确实可以用“if.. else”代替,但是使用“异常”还有其他好处(比如方便?)

谢谢你,对不起我的英语不好。

I'm new to programming and I have a conceptual question.

That is, can "exception" be perfectly replaced by "if.. else" ?

I know "exception" is to handling some exceptional conditions that might cause error or crash.

But we also use "if.. else" to ensure the correctness of value of variables, don't we?

Or "exception" can really be replaced by "if.. else", but using "exception" has other benefits(like convenience?)

Thank you, and sorry for my poor English.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

黒涩兲箜 2024-12-06 11:42:25

异常和“if..else”之间的最大区别在于异常会向上传递调用堆栈:一个函数中引发的异常可以在堆栈上任意数量的帧中被调用者捕获。使用“if”语句不允许您以这种方式转移控制,所有事情都必须在检测到条件的同一函数中处理。

The biggest difference between exceptions and "if..else" is that exceptions pass up the call stack: an exception raised in one function can be caught in a caller any number of frames up the stack. Using "if" statements doesn't let you transfer control in this way, everything has to be handled in the same function that detected the condition.

坦然微笑 2024-12-06 11:42:25

您的大多数问题都与 Python 相关,因此这里是基于该事实的答案。

在 Python 中,使用 try-except 块是惯用的(或“pythonic”)。我们称之为“EAFP”:请求宽恕比请求许可更容易

在 C 语言中,没有例外,通常是 "LBYL":三思而后行,导致大量 if (...) 语句。

因此,虽然您可以 LBYL,但您应该遵循您所编程语言的习惯用法:使用异常来处理异常情况,并使用 if 语句来处理条件。

Most of your questions relate to Python, so here is an answer based on that fact.

In Python, it is idiomatic (or "pythonic") to use try-except blocks. We call this "EAFP": Easier to ask for forgiveness than permission.

In C, where there were no exceptions, it was usual to "LBYL": Look before you leap, resulting in lots of if (...) statements.

So, while you can LBYL, you should follow the idioms of the language in which you are programming: using exceptions for handling exceptional cases and if-statements for conditionals.

庆幸我还是我 2024-12-06 11:42:25

从技术上讲,答案是肯定的,异常可以完美地用 if-else 代替。许多语言(例如 C)没有可引发和捕获的异常的本机概念。

异常的主要优点是代码的可读性和可维护性。它们的用途与 if-else 不同。异常用于异常情况,而 if-else 用于程序流程。

请参阅这篇优秀文章解释其中的差异。

Technically, the answer is yes, exceptions can be perfectly replaced by if-else. Many languages, C for example, have no native notion of exceptions that can be thrown and caught.

The primary advantage of exceptions is code readability and maintainability. They serve a different purpose than if-else. Exceptions are for exceptional conditions, while if-else is for program flow.

See this excellent article explaining the difference.

北城孤痞 2024-12-06 11:42:25

有很多分支条件需要管理。理论上,完美的代码不需要异常,但完美的代码在现实生活中并不存在。异常是一种以受控方式处理问题的完善机制。

That's a lot of branch conditions to manage. In theory, exceptions aren't necessary for perfect code, but perfect code does not exist in real life. Exceptions are a well-established mechanism for dealing with problems in a controlled manner.

紙鸢 2024-12-06 11:42:25

处理函数错误的旧方法看起来像这样:

int result = function_returns_error_code();
if (result != GOOD)
{
    /* handle problem */
}
else
{
   /* keep going */
}

这个解决方案(以及其他类似的解决方案 - 使用 if-else)的问题是,如果存在真正的问题,并且程序员没有正确地使用if...else(如果函数返回一个指示主要问题的错误代码,但程序员忘记了),它将被忽略。出现异常时,它会在调用堆栈中不断向上移动,直到它被处理或程序退出。

此外,检查函数中的错误代码或传递要放入错误代码的参数是乏味的。为了可维护性和抽象性,使用异常更简单、更清晰、更好。

The old way for handling an error from a function looks something like this:

int result = function_returns_error_code();
if (result != GOOD)
{
    /* handle problem */
}
else
{
   /* keep going */
}

The problem with this solution (and others like it - using if-else) is that if there is a real problem, and the programmer does not properly handle it with an if...else (if the function returns an error code indicating major problems, but the programmer forgets about it), it is left ignored. With an exception, it goes further and further up the call stack ) until it is either handled or the program quits.

Further, it is tedious to check for error codes in functions, or pass a parameter into which to put an error code. It is simpler, cleaner, and better to use exceptions, for maintainability and abstraction.

桃气十足 2024-12-06 11:42:25

在大多数高级语言中,处理异常通常比 if-else 更有效,因为可以避免多重验证。例如:

if value is not 0 then print 10 / value

在大多数解释器中,10 / value 将在使用之前内部测试 value 是否是有效的除法器所以你实际上已经对同一问题进行了两次测试。在某些情况下,异常可能完全来自硬件,因此根本不会发生软件验证。

另一方面:

try print 10 / value ... catch exception

只会测试一次 value 是否有效。此外,测试很有可能比您自己的代码得到更好的优化,并且更有能力处理真正的意外情况(例如内存不足错误)。

In most high-level languages working with exceptions is often more efficient than if-else because you avoid multiple validation. eg:

if value is not 0 then print 10 / value

In most interpreters 10 / value will internally test whether value is a valid divider before using it so you've actually tested for the same problem twice. In some cases the exception may come all the way up from hardware so no software validation is happening at all.

On the other hand:

try print 10 / value ... catch exception

Will only test whether value is valid once. Furthermore there's a good chance the test will be better optimised than your own code and more capable of handling truly unexpected conditions (like out of memory errors).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文