LoginSignup
1
0

More than 1 year has passed since last update.

Dart でのオリジナル例外、エラーの実装と型判定について

Posted at

はじめに

オリジナルの例外やエラーをスローするにはどうすればよい?それを判定するにはどうすればよい?を確かめてみました。

分かったこと

  1. Exceptionimplements する
  2. Errorextends する
  3. 型は is で判定
  4. 型は .runtimeType で表示可能
  5. 型判定メソッドの仮引数は dynamic にしておけばいい

検証

// オリジナルの例外 その1
class MyEx01 implements Exception {}

// オリジナルの例外 その2
class MyEx02 implements Exception {}

// オリジナルのエラー
class MyError extends Error {}

// 型判定メソッド
void _printEx(dynamic target) {
  if (target is MyEx01) {
    print('1. 「MyEx01」を検出');
  } else if (target is Exception) {
    print('2. 例外を検出 [${target.runtimeType}]');
  } else {
    print('3. 不明なオブジェクト [${target.runtimeType}]');
  }
}

void main() async {
  try {
    print('\n--- throw MyEx01(); ---');
    throw MyEx01();
  } catch (e) {
    _printEx(e);
  }

  try {
    print('\n--- throw MyEx02(); ---');
    throw MyEx02();
  } catch (e) {
    _printEx(e);
  }

  try {
    print('\n--- throw MyError(); ---');
    throw MyError();
  } catch (e) {
    _printEx(e);
  }

  try {
    print("\n--- throw 'Hello !!'; ---'");
    throw 'Hello !!';
  } catch (e) {
    _printEx(e);
  }
}
--- throw MyEx01(); ---
1. 「MyEx01」を検出

--- throw MyEx02(); ---
2. 例外を検出 [MyEx02]

--- throw MyError(); ---
3. 不明なオブジェクト [MyError]

--- throw 'Hello !!'; ---'
3. 不明なオブジェクト [String]

参考

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0