作为程序员,非常有必要做出无错的代码是非常必要的,而在一个大程序中发现错误是非常困难的。 Dart为程序员提供断言语句来检查错误。 assert 语句是调试代码的有用工具,它使用布尔条件进行测试。如果断言语句中的布尔表达式为真,则代码继续执行,但如果返回假,则代码以断言错误结束。
Syntax: assert(condition);
必须注意的是,如果要使用断言,则必须在执行时启用它,因为它只能在开发模式下使用,而不能在生产模式下使用。如果它没有被启用,那么它在执行时将被简单地忽略。
在通过 cmd 执行dart文件时启用断言:
dart --enable-asserts file_name.dart
示例 1:在dart程序中使用 assert。
Dart
void main()
{
String geek = "Geeks For Geeks";
assert(geek != "Geeks For Geeks");
print("You Can See This Line Geek as a Output");
}
Dart
void main()
{
String geek = "Geeks For Geeks";
assert(geek != "Geeks For Geeks", "Strings are equal So this message is been displayed!!");
print("You Can See This Line Geek as a Output if assert returns true");
}
启用断言时的输出:
Unhandled exception:
'file:///C:/Users/msaur/Desktop/GeeksForGeeks.dart': Failed assertion: line 4 pos 10: 'geek != "Geeks For Geeks"': is not true.
#0 _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:42:39)
#1 _AssertionError._throwNew (dart:core-patch/errors_patch.dart:38:5)
#2 main (file:///C:/Users/msaur/Desktop/GeeksForGeeks.dart:4:10)
#3 _startIsolate. (dart:isolate-patch/isolate_patch.dart:301:19)
#4 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:168:12)
通过cmd输出:
未启用断言时的输出:
You Can See This Line Geek as a Output
通过cmd输出:
除此之外,如果断言返回false,您还可以为案例发送消息:
assert(condition, "message");
当您尝试调试各种错误并想知道代码中哪个断言返回了错误时,它非常有用。
示例 2:在dart程序中使用 assert 给出消息。
Dart
void main()
{
String geek = "Geeks For Geeks";
assert(geek != "Geeks For Geeks", "Strings are equal So this message is been displayed!!");
print("You Can See This Line Geek as a Output if assert returns true");
}
输出:
C:\Users\msaur\Desktop>dart --enable-asserts GeeksForGeeks.dart
Unhandled exception:
'file:///C:/Users/msaur/Desktop/GeeksForGeeks.dart': Failed assertion: line 4 pos 10: 'geek !=
"Geeks For Geeks"': Strings are equal So this message is been displayed!!
#0 _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:42:39)
#1 _AssertionError._throwNew (dart:core-patch/errors_patch.dart:38:5)
#2 main (file:///C:/Users/msaur/Desktop/GeeksForGeeks.dart:4:10)
#3 _startIsolate. (dart:isolate-patch/isolate_patch.dart:301:19)
#4 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:168:12)
通过cmd输出: