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.
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.
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 .
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
).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With