What's the recommended way in Dart: asserts or throw Errors

前端 未结 4 882
攒了一身酷
攒了一身酷 2021-01-11 16:25

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

4条回答
  •  一整个雨季
    2021-01-11 17:05

    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.

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

    We can do:

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

    but can't do:

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

    Similarly, some sanity checks are relatively expensive.

    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.

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

    assert(someVeryExpensiveCheck());
    

提交回复
热议问题