Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print a message when an assert fails, in Dart?

Tags:

dart

We'd like to print a message when an assert() fails. Currently in Dart, an assert only takes a boolean. We'd like to give the developer explicit reasons and instructions for what to do when the assert fails.

like image 663
Seth Ladd Avatar asked Aug 24 '15 17:08

Seth Ladd


People also ask

How does assert work in darts?

The assert statement is a useful tool to debug the code and it uses boolean condition for testing. If the boolean expression in assert statement is true then the code continues to execute, but if it returns false then the code ends with Assertion Error.

Which is used to disrupt the execution in Dart assert?

assert is an incredibly useful statement that allows you to put conditions on code execution. It's used to disrupt normal execution when a boolean condition is false .


2 Answers

As of Dart 1.22, assert() takes an optional message.

assert(configFile != null, "Tool config missing.");

If the assertion fails, it will produce something like the following:

Unhandled exception:
'file:///.../main.dart': Failed assertion: line 9 pos 10:
'configFile != null': Tool config missing.
#0      _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:33)
#1      _AssertionError._throwNew (dart:core-patch/errors_patch.dart:29)
#2      main (file:///.../main.dart:9:10)

Note that the error message includes the actual assertion (configFile != null).

like image 123
filiph Avatar answered Oct 27 '22 04:10

filiph


Just to add, if you're executing a dart file via command line, you need to enable asserts as follows, see reference here:

dart --enable-asserts main.dart
like image 27
stt106 Avatar answered Oct 27 '22 05:10

stt106