Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

flutter

dart

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.

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

like image 799
Thomas Avatar asked Sep 07 '19 11:09

Thomas


People also ask

How do you throw a dart error?

Throwing an ExceptionThe throw keyword is used to explicitly raise an exception. A raised exception should be handled to prevent the program from exiting abruptly.

How do you handle errors in flutter?

Errors that don't occur within Flutter's callbacks can't be caught by the framework, but you can handle them by setting up a Zone . All errors caught by Flutter are routed to the FlutterError. onError handler. By default, this calls FlutterError.

Which is used to disrupt the execution in Dart?

Exception is a runtime unwanted event that disrupts the flow of code execution.

What is exception handling error in dart and flutter?

Dart Exceptions are the run-time error. It is raised when the program gets execution. The program doesn't report the error at compile time when the program runs internally and if Dart compiler found something not appropriate. Then, it reports run-time error and the execution of program is terminated abnormally.


1 Answers

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());
like image 181
Rémi Rousselet Avatar answered Oct 26 '22 08:10

Rémi Rousselet