【量】的修饰符
关键词:条件、循环、控制、异常处理、assert语句
·条件语句
if、if-else、switch-case
·循环语句
for、for-in、while、do-while
·控制语句
break、continue
·assert 语句
开发期间用来检查参数的,assert(condition,optionalMessage), 如果 condition 为 false, 那么将会抛出 [AssertionError]异常,停止执行程序。(通常只用于开发阶段,在运行时被忽略)
void main() {
var x = 5 / 2;
var x1 = 5 ~/ 2;
assert(x == 2, '测试x');
assert(x1 == 2, '测试x1');
}
//结果:
Failed assertion: line 48 pos 10: 'x == 2': 测试x
#0 _AssertionError._doThrowNew (dart:
core-patch/errors_patch.dart:42:39)
#1 _AssertionError._throwNew (dart:core-patch/errors_patch.dart:38:5)
#2 main (package:dartdemo/5_exception_main.dart:48:10)
#3 _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:307:19)
#4 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:174:12)
·异常处理语句
try-catch-finally、throw、rethrow
throw: 可以抛出任意对象
try-catch:捕获异常
finally: 确保某些代码一定能运行
rethrow: 抛给上一级处理
执行顺序为: 内层 exception - 内层 finally -> rethrow -> 外层 exception - 外层 finally
void main() {
try {
try {
List<String> numList = ['1', '2'];
print(numList[6]);
} on Exception catch (e) {
//通过on 关键词来指定异常类型
print('Exception details:\n $e');
} catch (e, s) {
//捕获异常对象
print('Exception details:\n $e');
//堆栈跟踪
print('Stack trace:\n $s');
rethrow; //抛给上一级处理
} finally {
print('Stack trace:finally');
}
} catch (e, s) {
//捕获异常对象
print('外层 Exception details:\n $e');
//堆栈跟踪
print('外层 Stack trace:\n $s');
} finally {
print('Stack trace:finally2222');
}
}