Dart中推荐的方法是:断言或引发错误 [英] What's the recommended way in Dart: asserts or throw Errors

查看:77
本文介绍了Dart中推荐的方法是:断言或引发错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Dart明确区分了Error和Exception,它们是代码逻辑中的一个问题,该问题永远不会发生,也永远不会被捕获,这是基于运行时数据的.

Dart explicitly makes a distinction between Error, that signals a problem in your code's logic and should never happen and should never be caught and Exceptions that signal a problem based on run-time data.

我真的很喜欢这种区别,但是我想知道什么时候应该使用assert()函数?

I really like this distinction but I wonder when should I then use assert() functions?

推荐答案

Asserts是仅在开发中执行代码而又不影响发布模式性能的方法-通常是防止类型系统中缺少功能而导致的不良状态

Asserts are ways to perform code useful in development only, without hindering the performances of release mode – usually to prevent bad states caused by a missing feature in the type system.

例如,只有断言可用于进行防御性编程 并提供const构造函数.

For example, only asserts can be used to do defensive programming and offer a const constructor.

我们可以做到:

class Foo {
  const Foo(): assert(false);
}

但不能:

class Foo {
  const Foo() { throw 42; }
}

类似地,一些健全性检查相对昂贵.

Similarly, some sanity checks are relatively expensive.

例如,在Flutter的上下文中,您可能想遍历小部件树以检查小部件祖先上的某些内容.但这是昂贵的,因为这仅对开发人员有用.

In the context of Flutter, for example, you may want to traverse the widget tree to check something on the ancestors of a widget. But that's costly, for something only useful to a developer.

在assert中进行检查,既可以提高发行版的性能,又可以提高开发的实用性.

Doing that check inside an assert allows both performance in release, and utility in development.

assert(someVeryExpensiveCheck());

这篇关于Dart中推荐的方法是:断言或引发错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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