你的dart代碼可以拋出和捕獲異常。異常指一些出乎意料的事情發(fā)生了野哭。通常如果一個異常未被捕獲時回終止程序或者當(dāng)前的isolate(類似類似線程的東西)
與Java相反,所有的dart異常都是未受檢異常拿霉。也就是說當(dāng)調(diào)用一個可以拋出異常的方法時,不必一定去捕獲這個異常同云。這點(diǎn)和Kotlin一樣,都是為了簡化代碼堵腹,增加可讀性炸站。如果你擔(dān)心這段代碼真的會產(chǎn)生什么異常,那么可以自行捕獲疚顷。
Dart提供了Exception
和Error
兩種類型旱易,并且提供了許多預(yù)定義的子類。當(dāng)然你也可以定義自己的異常腿堤。然而Dart程序允許你將任何非空對象當(dāng)作異常拋出阀坏,而非只有Exception和Error才能拋出。
Throw
這是一個拋出的用例:
throw FormatException('Expected at least 1 section');
你也可以拋出一個隨意的對象:
throw 'Out of llamas!';
注意:產(chǎn)品質(zhì)量的代碼通常拋出實(shí)現(xiàn)了Exception和Error的異常笆檀。
throw
其實(shí)是表達(dá)式忌堂,他可以出現(xiàn)在表達(dá)式出現(xiàn)的任何地方:
void distanceTo(Point other) => throw UnimplementedError();
或者是這樣:
person?.run()??throw 'person is null';
catch
catch
用來捕獲異常,這和通常的語言語義相通误债。
try {
breedMoreLlamas();
} on OutOfLlamasException {
buyMoreLlamas();
}
捕獲多種異常時如果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');
}
前面代碼我們看到捕獲異常可以用on
或者catch
或者兩者都用寝蹈,on
可以明確指定你要捕獲的異常類型李命,catch
則可以使用異常對象。
catch還有第二個參數(shù)箫老,他表示堆棧跟蹤:
try {
// ···
} on Exception catch (e) {
print('Exception details:\n $e');
} catch (e, s) {
print('Exception details:\n $e');
print('Stack trace:\n $s');
}
如果想在捕獲異常的時候繼續(xù)傳播這個異常封字,可以使用rethrow
關(guān)鍵字:
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
若要確保無論是否引發(fā)異常,都運(yùn)行一些代碼耍鬓,請使用finally子句阔籽。如果沒有catch子句與異常匹配,則異常將在finally子句運(yùn)行后傳播:
try {
breedMoreLlamas();
} finally {
// Always clean up, even if an exception is thrown.
cleanLlamaStalls();
}
finally
子句會在catch
后面執(zhí)行牲蜀。
try {
breedMoreLlamas();
} catch (e) {
print('Error: $e'); // Handle the exception first.
} finally {
cleanLlamaStalls(); // Then clean up.
}
更多關(guān)于異常的信息參考dart庫部分的Exception