Dart中的错误与异常 [英] Error vs. Exception in Dart

查看:155
本文介绍了Dart中的错误与异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么Dart中有错误和异常,而没有错误或异常?

Why are there Errors AND Exceptions in Dart and not either Errors OR Exceptions?

历史原因是什么?

我可以抛出一个错误,我可以抛出一个异常。分析器不会像Java中那样检查它们(异常与RuntimeException)

I can throw an Error, I can throw an Exception. None of them is checked by the Analyzer like in Java (Exception vs. RuntimeException)

推荐答案

来自这篇文章,引用Bob Nystrom:

From this post, quoting Bob Nystrom:


错误及其子类用于程序错误。如果这些
之一发生,则说明您的代码很糟糕,应该修复您的代码。

Error and its subclasses are for programmatic errors. If one of those occurs, your code is bad and you should fix your code.

非错误异常类用于运行时错误。有时您可以
防止它们被抛出,但是通常您不能。

Non-Error exception classes are for runtime errors. Sometimes you can prevent them from being thrown, but often you cannot.

除了在某些特殊情况下,惯用的Dart应当抛出
错误,但永远不要抓住他们。专门存在这些漏洞是为了避免被
捕获,以便他们关闭应用程序并提醒程序员该漏洞的
位置。

Except in a few special circumstances, idiomatic Dart should throw Errors, but never catch them. They exists specifically to not be caught so that they take down the app and alert the programmer to the location of the bug.

换句话说,您应该期待(并检查)异常(旨在处理异常)。如果遇到错误,则需要检查引发错误的API的使用方式-您可能使用的是错误的。

In other words, you should expect (and check for) exceptions (it is intended that you should handle them). If you get an error, then you need to check how you're using the API that's throwing the error - you're probably using it wrong.

编写API,则应使用相同的模式。错误是向下游开发人员发送的有关他们如何使用您的API的消息。

If you're writing an API, then you should use the same pattern. Errors are messages to downstream developers about how they are using your API.

这篇关于Dart中的错误与异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆