1. 程式人生 > >6.Exceptions-異常(Dart中文文件)

6.Exceptions-異常(Dart中文文件)

異常是用於標識程式發生未知異常。如果異常沒有被捕獲,If the exception isn’t caught, the isolate that raised the exception is suspended, and typically the isolate and its program are terminated.

對比java,Dart的異常都是未檢查異常,方法不需要定義要丟擲的異常型別,呼叫時也沒有要求捕獲異常。

Dart提供了Exception和Error的異常類,你也可以定義自己的異常。同時,Dart的異常丟擲,不僅僅只能是繼承至Exception或者Error的類,任意類物件都可以作為異常丟擲。

Throw

throw FormatException('Expected at least 1 section');

你也可以丟擲任意物件

throw 'Out of llamas!';

注意:雖然異常可以丟擲任意物件,但是一般來說還是要丟擲繼承於Error或者Exception的物件

因為throw an exception是一個表示式,所以它可以在箭頭函式的簡化寫法。

void distanceTo(Point other) => throw UnimplementedError();

Catch

捕獲異常可以終止異常的傳遞(除非你重新拋異常)。

try {
  breedMoreLlamas();
} on OutOfLlamasException {
  buyMoreLlamas();
}

捕獲異常時,可以定義多個異常型別的捕獲處理,丟擲的異常匹配到一個異常型別後,就不繼續往下匹配了。如果你沒有指定捕獲的異常型別,將匹配任意型別。

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 exception型別 或者catch(e),再或者兩個都有的異常捕獲寫法。on可以區分異常型別,catch可以獲取異常物件。

其中,catch可以獲取兩個物件,第一個是異常物件,第二個是錯誤堆疊。

try {
  // ···
} on Exception catch (e) {
  print('Exception details:\n $e');
} catch (e, s) {
  print('Exception details:\n $e');
  print('Stack trace:\n $s');
}

如果catch後,需要將異常丟擲到外層,可以用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

為了確保程式碼無論是正常或者丟擲異常都可以執行,請使用finally.如果程式碼中,catch匹配的異常,它將會在執行finally後,繼續向上層丟擲異常。

try {
  breedMoreLlamas();
} finally {
  // Always clean up, even if an exception is thrown.
  cleanLlamaStalls();
}

try {
  breedMoreLlamas();
} catch (e) {
  print('Error: $e'); // Handle the exception first.
} finally {
  cleanLlamaStalls(); // Then clean up.
}

第七篇翻譯 Classes 類 Dart的核心部分