|

Dartの勉強9:例外処理

DartのHPでは、用意されているExceptionは6つあるようです。
①DeferredLoadException
②FormatException
③IntegerDivisionByZeroException
④IOException
⑤IsolateSpawnException
⑥TimeoutException

void main() {
  int a =5;
  int b=0;
  int c=a~/b;
  print("The result is $c.");
}

このコードは以下の通りエラーになります。太字のところに例外のタイプが出ています。
Unhandled exception:
IntegerDivisionByZeroException
#0 int.~/ (dart:core/runtime/libintegers.dart:18:7)
#1 main (file:///D:/MySource/dart/test/test3.dart:5:10)
#2 _startIsolate. (dart:isolate/runtime/libisolate_patch.dart:300:19)
#3 _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:171:12)

なので、エラーの際にExceptionが投げられる(throw)ので、これをcatchして、プログラムが止まらないようにします。問題となりそうな動作を開始する前にtryを入れます。

void main() {
  int a = 5;
  int b = 0;
  //例外のタイプが分かっている場合は「on」を使って、プログラムを止めずに処理を引き継ぎます。
  print("CASE 1");
  try {
    int c = a ~/ b;
    print("The result is $c.");
  } on IntegerDivisionByZeroException {
    print("Don't devide by Zero!");
  }

  //例外のタイプが分かってない場合は「catch」を使って、例外のタイプを取得し表示。
  print("\nCASE 2");
  try {
    int c = a ~/ b;
    print("The result is $c.");
  } catch (e) {
    print("The exception thrown is $e");
  }

  //例外のタイプが分かってない場合は「catch」を使って、例外のタイプを取得し表示し、また、エラーメッセージも表示
  print("\nCASE 3");
  try {
    int c = a ~/ b;
    print("The result is $c.");
  } catch (e, s) {
    print("The exception thrown is $e");
    print("STACK TRACE\n $s");
  }

  //例外のタイプが分かってない場合は「catch」を使って、例外のタイプを取得し表示し、また、エラーメッセージも表示
  print("\nCASE 4");
  try {
    int c = a ~/ b;
    print("The result is $c.");
  } catch (e) {
    print("The exception thrown is $e");
  } finally {
    print("Finally Clause is always executed.");
  }

  //カスタム例外処理
  print("\nCASE 5");
  try {
    inputValue(-20);
  }catch(e){
    print(e.errorMessage());
  }
}

class InputValueException implements Exception {
  String errorMessage() {
    return "You cannot enter a number less than 0.";
  }
}

void inputValue(int size) {
  if (size < 0) {
    throw new InputValueException();
  } else {
    print("The size is $size.");
  }
}

ちょっと長いですが、tryシリーズをてんこ盛りにしました。
最初から例外のタイプが分かっている場合は「on」で引き継ぎ、分からない場合は「catch(e,s)」で例外タイプやエラーメッセージを取得してから次を考える。「finally」絶対やっておきたい処理を入れておく場所で、自分でエラーを設定したいときはクラスを作る。という感じです。処理結果は以下の通りです。
CASE 1
Don’t devide by Zero!

CASE 2
The exception thrown is IntegerDivisionByZeroException

CASE 3
The exception thrown is IntegerDivisionByZeroException
STACK TRACE
#0 int.~/ (dart:core/runtime/libintegers.dart:18:7)
#1 main (file:///D:/MySource/dart/test/test3.dart:25:15)
#2 _startIsolate. (dart:isolate/runtime/libisolate_patch.dart:300:19)
#3 _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:171:12)

CASE 4
The exception thrown is IntegerDivisionByZeroException
Finally Clause is always executed.

CASE 5
You cannot enter a number less than 0.

類似投稿

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

This site uses Akismet to reduce spam. Learn how your comment data is processed.