流程控制
Control Flow与Java基本一样,甚至for-in
的使用也无差。
Iterable
实例可以像Kotlin一样使用foreach
,不需要获取当前i
时,可以使用
candidates.forEach((candidate) => candidate.interview());
Dart中switch-case
的用法上与Java有少许区别,需注意:
switch
后必须跟编译时常量,类型上无限制
(int
、string
、enum
或其他可以用常量构造函数
创建的实例,但要求此类型不能重写==
,因为switch基于==
进行比较,重写==
有可能会违反互换性原则,即父类 == 子类
但子类型 !== 父类型
)case
之后必须要跟break
或者continue
default
可省略(与Java相同)contine label;
语句可以跳转到label:
的位置
(可以弥补Java中省略break时进入下一个case的功能)
var command = 'CLOSED';
switch (command) {
case 'CLOSED':
executeClosed();
continue nowClosed;
// Continues executing at the nowClosed label.
nowClosed:
case 'NOW_CLOSED':
// Runs for both CLOSED and NOW_CLOSED.
executeNowClosed();
break;
}
异常
与Kotlin相似,Dart中所有的异常都是未检查的异常,方法不声明它们可能抛出哪些异常,也不要强制捕获任何异常。
Dart可以抛出任何非空对象,不仅仅是Exception和Error
//抛出异常的例子:
throw FormatException('Expected at least 1 section');
//也可以抛出任意对象:
throw 'Out of llamas!';
throw语句是一个表达式,所以可以出现在=>中
void distanceTo(Point other) => throw UnimplementedError();
可以使用on
、catch
或者on...catch
捕捉异常:
try {
breedMoreLlamas();
} on OutOfLlamasException {
// A specific exception
buyMoreLlamas();
} on Exception catch (e) {
// Anything else that is an exception
print('Unknown exception: $e');
} catch (e) {
// No specified type, handles all
print('Something really unknown: $e');
}
要在捕获中处理异常,同时允许其继续传播,使用rethrow
关键字。
void misbehave() {
try {
dynamic foo = true;
print(foo++); // Runtime error
} catch (e) {
print('misbehave() partially handled ${e.runtimeType}.');
rethrow; // Allow callers to see the exception.
}
}
void main() {
try {
misbehave();
} catch (e) {
print('main() finished handling ${e.runtimeType}.');
}
}
finally
的使用与Java无差别