Thuta Learning
Dart
AdvancedProgrammingအခြေခံ

Sealed Types & Error Handling

Dartသင်ခန်းစာ 2040 မိနစ်

ဒီခန်းပြီးရင် ဘာတတ်သွားမလဲ

  • Sealed class hierarchy တစ်ခု ကြေညာပြီး သူ့အပေါ် exhaustive switch expression ရေးနိုင်ဖို့
  • Subtype အသစ်ထပ်ထည့်တဲ့အခါ compiler က ဘာကို အာမခံပေးလဲ ရှင်းပြနိုင်ဖို့
  • Exception (ပြန်ကောင်းနိုင်တဲ့ အခြေအနေ) နဲ့ Error (bug) ကို ခွဲခြားပြီး Exception ကို implements လုပ်တဲ့ custom exception ရေးနိုင်ဖို့
  • try, on, catch, finally နဲ့ rethrow ကို သုံးပြီး cleanup အမြဲ run အောင်၊ မူလ failure မပျောက်အောင် လုပ်နိုင်ဖို့

ရိုးရိုးလေး ရှင်းပြမယ်

Sealed type နဲ့ error handling ကို ရိုးရိုးလေး ပြောရရင်

Sealed class ဆိုတာ 'မိသားစု အဖွဲ့ဝင်တွေကို ရေလို့ရတဲ့' class ပါ။ Outcome ဆိုတဲ့ sealed class ရဲ့ subtype တွေက Valid နဲ့ Invalid ပဲဆိုရင် compiler က အဲဒီနှစ်ခုကိုပဲ သိပါတယ်၊ ဒါကြောင့် switch တစ်ခုက နှစ်ခုလုံးကို ကိုင်ထားလား ဆိုတာ သူ့ဘာသာ စစ်ပေးနိုင်ပါတယ်။ ဘယ်ဟာမှ မကျန်စေဖို့ စစ်ဆေးတဲ့အလုပ်ကို လူက မလုပ်ရတော့ပါဘူး။

Error handling ကတော့ တစ်ခုခု မှားသွားတဲ့အခါ throw နဲ့ object တစ်ခု ပစ်ထုတ်ပြီး try/catch နဲ့ ဖမ်းတာပါ။ ဒီအပိုင်းနှစ်ခုက အတူတူ ရည်ရွယ်ချက်တစ်ခုကို ဆောင်ရွက်ပါတယ်: ကွဲပြားမှုနဲ့ မအောင်မြင်မှုတွေကို ဖုံးကွယ်မထားဘဲ code ထဲမှာ ထင်ထင်ရှားရှား ဖော်ပြဖို့ပါ။

Problem → Why → Solution

ပြဿနာ: flag တွေနဲ့ ဖြစ်မနေရတဲ့ state တွေ

Screen တစ်ခုက loading, ready (item list ပါ), failed (message ပါ) ဆိုတဲ့ အခြေအနေ သုံးမျိုး ရှိပါတယ်။ ရိုးရိုးအားဖြင့် bool isLoading, String? error, List<String>? items သုံးခုကို class တစ်ခုထဲ ထည့်ကြပါတယ်။ ဒါပေမဲ့ အဲဒီ field သုံးခုက ပေါင်းစပ်ပုံ ရှစ်မျိုး ဖြစ်နိုင်ပြီး တကယ်ဖြစ်သင့်တာက သုံးမျိုးပဲ၊ isLoading true ဖြစ်နေရင်း error ပါနေတာမျိုးကို ဘယ်သူမှ မတားပါဘူး။

Error ကို ကိုင်တွေ့တဲ့ code ကလည်း ဒီအတိုင်းပါပဲ: try { ... } catch (e) { } လို့ အလွတ်ရေးထားရင် bug ဖြစ်တာနဲ့ ဖြစ်သင့်တဲ့ failure တွေ နှစ်ခုလုံး ပျောက်သွားပြီး ဘာကြောင့် မအလုပ်လုပ်တာလဲ ဆိုတာ ဘယ်သူမှ မသိနိုင်တော့ပါဘူး။

flags.dart
class ScreenState {
  bool isLoading = true;
  String? error;
  List<String>? items;
}

String label(ScreenState s) {
  if (s.isLoading) return 'Loading';
  if (s.error != null) return 'Error: ${s.error}';
  return 'Ready: ${s.items!.length}'; // crashes if items is null: a state nobody meant
}

void save() {
  try {
    // ...write to disk...
  } catch (e) {
    // ignored: a typo here would vanish without a trace
  }
}

ဖြစ်မနေရတဲ့ state တွေကို type နဲ့ ဖယ်ရှားပါ

Flag နဲ့ nullable field တွေက ဖြစ်မနေရတဲ့ ပေါင်းစပ်မှုကို ဖန်တီးခွင့်ပေးလို့ s.items! လို ပြေလည်ဖို့ ! တွေကို ပြန်ထည့်ရပါတယ်။ Sealed hierarchy ကတော့ state တစ်ခုချင်းစီကို type တစ်ခုအဖြစ် ပေးပြီး ကိုယ်လိုတဲ့ data ကိုပဲ ထည့်ထားလို့ Failed မှာ items မရှိ၊ Ready မှာ error မရှိပါဘူး။ Switch တိုင်းကလည်း case အားလုံးကို ကိုင်ဖို့ compiler က အတင်းတောင်းပါတယ်။

Core concept: sealed, exhaustiveness, Exception နဲ့ Error

sealed class Outcome {} ကို ကြေညာရင် Outcome ကို ကိုယ်တိုင် instance မဆောက်နိုင်ဘူး (abstract လိုမျိုး) ပြီး သူ့ကို extends, implements လုပ်နိုင်တာက အဲဒီ library ထဲက class တွေပဲ ဖြစ်ပါတယ်။ ဒါကြောင့် subtype အားလုံးကို compiler က သိပါတယ်။ Outcome ကို switch လုပ်တဲ့အခါ subtype တစ်ခုချင်းကို case တစ်ခုစီနဲ့ ကိုင်ရပါမယ်၊ ကျန်နေရင် compile error ပါ။ Subtype တွေမှာ ကိုယ်ပိုင် field တွေ ထားလို့ရပြီး pattern နဲ့ Valid(age: var a) လို ခွဲထုတ်လို့ရပါတယ်။ Result<T> လို generic sealed class လည်း ရေးလို့ရပါတယ်။

Dart မှာ ဘယ် object ကိုမဆို throw လုပ်လို့ရပေမဲ့ ဓလေ့အရ အမျိုးအစားနှစ်ခု ခွဲပါတယ်။ Exception ဆိုတာ ခေါ်သူက ကိုင်တွယ်နိုင်တဲ့ ပြန်ကောင်းနိုင်တဲ့ အခြေအနေ (FormatException၊ ကိုယ်ရေးတဲ့ custom exception)၊ Error ကတော့ program ရေးထားတာ မှားနေတယ်ဆိုတဲ့ bug (ArgumentError, StateError, RangeError, TypeError) ဖြစ်လို့ ဖမ်းပြီး ဖုံးထားတာထက် code ကို ပြင်သင့်ပါတယ်။ ကိုယ့် exception ကို class MyProblem implements Exception လို့ ရေးပါတယ်၊ Exception ကို extend မလုပ်နိုင်ပါဘူး (lesson 16 မှာ တွေ့ခဲ့ပြီးပြီ)။

try ဘလောက်က code ကို run ပြီး throw ဖြစ်ရင် ဒီ function ကနေ ချက်ချင်း ထွက်သွားကာ catch clause တွေကို အပေါ်ကနေ စစ်ပါတယ်။ on Type က type နဲ့ ပိုင်းခြားပြီး (on FormatException catch (e)) ပထမ ကိုက်တာက အလုပ်လုပ်ပါတယ်၊ catch (e, st) မှာ ဒုတိယ parameter က stack trace ပါ။ finally ကတော့ အောင်မြင်သည်ဖြစ်စေ၊ ပျက်သည်ဖြစ်စေ၊ return လုပ်ပြီးသည်ပင်ဖြစ်စေ အမြဲ run ပါတယ်။ rethrow ကတော့ ဖမ်းထားတဲ့ exception ကို မူလ stack trace နဲ့ အတူ ပြန်ပစ်တာပါ။

ဘယ် catch ကမှ မဖမ်းတဲ့ exception က program ကို ရပ်ပစ်ပါတယ်: dart run က "Unhandled exception:" ကို stderr ထုတ်ပြီး exit code 255 နဲ့ ထွက်ပါတယ် (ပြန်ထုတ်ကြည့်ထားပါတယ်)။ ဒါကြောင့် ပြန်ကောင်းနိုင်တဲ့ failure ကို ကိုင်တွယ်ပြီး bug ကိုတော့ ဖော်ပြစေပါ၊ ဒါ့အပြင် မအောင်မြင်မှုကို ပုံမှန်ရလဒ်တစ်ခုအဖြစ် ပြန်ပေးချင်ရင် Result လို sealed type ကို သုံးပါ။

ExceptionError
အဓိပ္ပာယ်ခေါ်သူ ကိုင်တွယ်နိုင်တဲ့ အခြေအနေProgram ထဲက bug
ဥပမာFormatException, ကိုယ်ရေးတဲ့ exceptionArgumentError, StateError, RangeError
ပုံမှန် ကိုင်တွယ်ပုံဖမ်းပြီး ပြန်ကောင်းအောင်လုပ် ဒါမှမဟုတ် အကြောင်းကြားပြင်ပါ၊ ထိပ်ဆုံးမှာမှ log ဖမ်းပါ
ပိတ်ထားတဲ့ မိသားစုနဲ့ လုံခြုံရေးကွန်ရက်
  1. Sealed: မိသားစု ပိတ်ထား
  2. switch က အဖွဲ့ဝင်တိုင်းကို ကိုင်ရမယ်
  3. throw က လက်ရှိ function ကနေ ထွက်
  4. on က handler ရွေး၊ finally က အမြဲ run

Subtype အသစ်တစ်ခုက မပြင်ရသေးတဲ့ switch တိုင်းကို compile မှာပဲ ကျိုးစေပေမဲ့ exception type အသစ်ကတော့ အဲဒီ type ကို ကိုင်မယ့် handler ရှိမှသာ သက်ရောက်ပါတယ်။

အထွေထွေ ပုံစံ

dart
sealed class Name {}
class CaseA extends Name { CaseA(this.data); final Type data; }
class CaseB extends Name {}
Result f(Name n) => switch (n) {
      CaseA(:var data) => value,
      CaseB() => value,
    };
class Problem implements Exception { Problem(this.detail); final String detail; }
try {
  risky();
} on Problem catch (e, stack) { handle(e); rethrow; }
finally { cleanup(); }

Sealed class က subtype တွေရဲ့ အစုကို ပိတ်ပြီး switch က case တိုင်းကို ဖော်ပြရပါတယ်။ Custom exception က Exception ကို implements လုပ်ပြီး try ဘလောက်ရဲ့ on ကနေ type အလိုက် ဖမ်းကာ finally မှာ cleanup လုပ်ပါတယ်။

Worked example: အသက်ကို စစ်ပြီး ရလဒ်ကို sealed type နဲ့ ပြန်ခြင်း

parseAge က မှားတဲ့ input ကို InvalidAge exception နဲ့ throw လုပ်ပါတယ်။ check function က အဲဒါကို ဖမ်းပြီး sealed type Outcome (Valid ဒါမှမဟုတ် Invalid) အဖြစ် ပြောင်းပြန်ပေးပါတယ်၊ ဒါကြောင့် ကျန်တဲ့ code က exception ကို ထပ်မကိုင်ရတော့ပါဘူး။ Output ထဲက checked line တွေက finally block အမြဲ run တာကို ပြပါတယ်။

outcomes.dart
// An Exception: a problem the caller can reasonably handle.
class InvalidAge implements Exception {
  InvalidAge(this.input, this.reason);

  final String input;
  final String reason;

  @override
  String toString() => 'InvalidAge("$input": $reason)';
}

int parseAge(String input) {
  final age = int.tryParse(input.trim());
  if (age == null) throw InvalidAge(input, 'not a number');
  if (age < 0 || age > 150) throw InvalidAge(input, 'out of range');
  return age;
}

// A sealed type: the compiler knows every possible subtype.
sealed class Outcome {}

class Valid extends Outcome {
  Valid(this.age);

  final int age;
}

class Invalid extends Outcome {
  Invalid(this.error);

  final InvalidAge error;
}

Outcome check(String input) {
  try {
    return Valid(parseAge(input));
  } on InvalidAge catch (e) {
    return Invalid(e);
  } finally {
    print('checked "$input"');
  }
}

// Exhaustive: delete a case and this stops compiling.
String report(Outcome outcome) => switch (outcome) {
      Valid(age: var a) when a >= 18 => 'adult, $a',
      Valid(age: var a) => 'minor, $a',
      Invalid(error: InvalidAge(reason: var r)) => 'rejected: $r',
    };

void main() {
  for (final input in ['42', '12', 'abc', '200']) {
    print(report(check(input)));
  }
}

Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်

  1. Custom exceptionclass InvalidAge implements Exception {

    Exception ကို implements လုပ်ထားလို့ on InvalidAge နဲ့ ဖမ်းလို့ရပြီး input နဲ့ reason ကို field အဖြစ် သယ်ပေးပါတယ်။ extends Exception မလုပ်နိုင်ပါဘူး။

  2. Throwif (age == null) throw InvalidAge(input, 'not a number');

    int.tryParse က parse မရရင် exception မထုတ်ဘဲ null ပေးလို့ ကိုယ့် exception ကို ကိုယ်တိုင် throw လုပ်ပါတယ်။ throw လုပ်တာနဲ့ parseAge ထဲက ကျန်တဲ့ line တွေ မ run တော့ပါဘူး။

  3. Catch by type} on InvalidAge catch (e) {

    InvalidAge ကိုပဲ ဖမ်းပါတယ်။ တခြား exception (ဥပမာ bug ကြောင့်ဖြစ်တဲ့ Error) ဆိုရင် ဒီ clause ကို ကျော်ပြီး အပေါ်ကို ဆက်သွားပါတယ်။

  4. Finallyprint('checked "$input"');

    finally ထဲက print က return Valid(...) လုပ်ပြီးတဲ့အခါလည်း၊ return Invalid(e) လုပ်ပြီးတဲ့အခါလည်း run ပါတယ်။ File ပိတ်တာ၊ connection ပြန်လွှတ်တာလို cleanup ကို ဒီမှာ ထားပါတယ်။

  5. Sealed typesealed class Outcome {}

    Outcome ရဲ့ subtype က Valid နဲ့ Invalid နှစ်ခုပဲ ဖြစ်တာကို compiler သိပါတယ်။ ဒီ library ပြင်ပက class က Outcome ကို extend လုပ်လို့ မရပါဘူး။

  6. Guard and nested patternInvalid(error: InvalidAge(reason: var r)) => 'rejected: $r',

    Pattern က Invalid ထဲက error ကို ဖွင့်ပြီး အဲဒီထဲက reason ကိုပါ r အဖြစ် ထုတ်ပေးပါတယ်။ Valid ရဲ့ case နှစ်ခုကို when guard နဲ့ ခွဲထားပြီး case သုံးခုလုံးက Outcome ကို ပြည့်စုံစွာ ကိုင်ပါတယ်။

You should see
checked "42"
adult, 42
checked "12"
minor, 12
checked "abc"
rejected: not a number
checked "200"
rejected: out of range

Exception လား Error လား: ဘာကို ဘယ်လို ဖမ်းမလဲ

အောက်က attempt function က throw ဖြစ်တာ ဘယ်အမျိုးအစားလဲ ခွဲပြီး print ထုတ်ပါတယ်။ on Exception ကို on Error ရှေ့မှာ ထားပြီး နောက်ဆုံးမှာ catch (e) ကို ထားပါတယ်၊ catch (e) မှာ Exception မှမဟုတ် Error လည်း မဟုတ်တဲ့ object (string လို) ကို ဖမ်းပါတယ်။ int.parse က FormatException ပစ်ပြီး list ရဲ့ မရှိတဲ့ index က RangeError၊ ဗလာ list ရဲ့ first က StateError ဖြစ်ပါတယ်။

exception_or_error.dart
class InvalidAge implements Exception {}

void attempt(String label, void Function() action) {
  try {
    action();
    print('$label: ok');
  } on Exception catch (e) {
    print('$label: Exception -> ${e.runtimeType}');
  } on Error catch (e) {
    print('$label: Error -> ${e.runtimeType}');
  } catch (e) {
    print('$label: other -> $e');
  }
}

void main() {
  attempt('parse', () => int.parse('abc'));
  attempt('index', () => <int>[1][5]);
  attempt('state', () => <int>[].first);
  attempt('argument', () => throw ArgumentError('bad'));
  attempt('custom', () => throw InvalidAge());
  attempt('string', () => throw 'just a string');
}
text
parse: Exception -> FormatException
index: Error -> RangeError
state: Error -> StateError
argument: Error -> ArgumentError
custom: Exception -> InvalidAge
string: other -> just a string

ဒီထဲက index ကို on Exception နဲ့ပဲ ဖမ်းမယ်ဆိုရင် မဖမ်းမိပါဘူး၊ RangeError က Exception မဟုတ်လို့ပါ။ ဒါက ရည်ရွယ်ချက်ရှိတာပါ: bug ကို ပြင်လို့ မရဘဲ ဖုံးကွယ်မထားစေချင်လို့ပါ။ throw 'just a string' လို Exception မဟုတ်တဲ့ object ကို throw လုပ်လို့ ရပေမဲ့ catch ဘက်မှာ ဘာ type နဲ့မှ ရွေးလို့ မရတော့လို့ ရှောင်ပါ။

try, catch, finally နဲ့ rethrow ကို အစီအစဉ်အတိုင်း

process function က input ကို parse လုပ်ပြီး FormatException ဖြစ်ရင် မှတ်တမ်းတင်ကာ rethrow နဲ့ ခေါ်သူဆီ ပြန်ပစ်ပါတယ်၊ finally မှာ cleanup ကို အမြဲ လုပ်ပါတယ်။ main ထဲက caller က နောက်ထပ် ဖမ်းပါတယ်။ အလုပ်ဖြစ်တဲ့ အစီအစဉ်ကို output က အတိအကျ ပြပါတယ်။

try_finally_rethrow.dart
void process(String input) {
  try {
    print('start $input');
    final n = int.parse(input);
    print('parsed $n');
  } on FormatException catch (e) {
    print('bad format: ${e.message}');
    rethrow; // same exception, same stack trace
  } finally {
    print('cleanup $input');
  }
}

int f() {
  try {
    return 1;
  } finally {
    print('cleanup'); // runs before f() actually returns
  }
}

void main() {
  for (final s in ['7', 'x7']) {
    try {
      process(s);
    } catch (e) {
      print('caller saw ${e.runtimeType}');
    }
  }
  print(f());
}
text
start 7
parsed 7
cleanup 7
start x7
bad format: Invalid radix-10 number
cleanup x7
caller saw FormatException
cleanup
1

ဒီမှာ သတိပြုစရာနှစ်ခု ရှိပါတယ်။ ပထမ catch ထဲမှာ throw e လို့ ရေးမယ့်အစား rethrow ကို သုံးပါ၊ rethrow က မူလ stack trace ကို ထိန်းထားလို့ failure ဘယ်ကစလဲ ဆက်ရှာလို့ရပါတယ်။ ဒုတိယ finally က f() ရဲ့ return 1 ပြီးတဲ့အခါလည်း run လို့ cleanup ကို အရင် print ထုတ်ပြီးမှ 1 ကို print ထုတ်ပါတယ်။ dart run မှာ ဒီ exception message ကို FormatException ရဲ့ message property ကနေ ယူထားတာပါ။

Sealed generic: Result<T> နဲ့ exception ကို ဘယ်အချိန် ရွေးမလဲ

မအောင်မြင်မှုက ပုံမှန်ဖြစ်လေ့ရှိတဲ့ ရလဒ်ဆိုရင် (user ရိုက်ထည့်တဲ့ text ကို parse လုပ်တာလို) exception ပစ်စရာ မလိုဘဲ sealed Result<T> ကို ပြန်ပေးလို့ ရပါတယ်။ ခေါ်သူက ok နဲ့ error နှစ်ခုလုံး ကိုင်ဖို့ switch က တောင်းဆိုပါတယ်။ final class နဲ့ ကြေညာထားတာကလည်း Ok နဲ့ Err ကို ဒီ library ပြင်ပက extend မလုပ်စေနိုင်ဖို့ပါ။

result.dart
sealed class Result<T> {}

final class Ok<T> extends Result<T> {
  Ok(this.value);

  final T value;
}

final class Err<T> extends Result<T> {
  Err(this.message);

  final String message;
}

Result<int> parseInt(String text) {
  final n = int.tryParse(text);
  return n == null ? Err('"$text" is not a number') : Ok(n);
}

String show(Result<int> r) => switch (r) {
      Ok(:var value) => 'ok $value',
      Err(:var message) => 'error: $message',
    };

void main() {
  print(show(parseInt('12')));
  print(show(parseInt('1x')));

  final results = [parseInt('1'), parseInt('2'), parseInt('z')];
  final oks = results.whereType<Ok<int>>().map((r) => r.value).toList();
  print(oks);
}
အခြေအနေရွေးရမယ့်နည်း
မအောင်မြင်တာက ပုံမှန်ရလဒ်၊ ခေါ်သူက တိုက်ရိုက်ကိုင်တွယ်Result လို sealed type
ဖြစ်မနေရတဲ့ အခြေအနေ၊ အလွှာအနည်းငယ် ကျော်သွားရမယ့် failureException ကို throw
Program ရေးထားတာ မှားနေတာ (bug)Error (ArgumentError, StateError) ကို throw

Sealed type ကို switch လုပ်တဲ့နေရာ တစ်ခုမှာ subtype တစ်ခု မပါရင် compiler က ဘယ်ဟာ ကျန်လဲ အတိအကျ ပြောပါတယ်: Outcome မှာ Skipped ကို ထပ်ထည့်ပြီး switch က Valid() နဲ့ Invalid() ကိုပဲ ကိုင်ထားရင် "The type 'Outcome' is not exhaustively matched by the switch cases since it doesn't match 'Skipped()'." လို့ ပြောပါတယ် (ပြန်ထုတ်ကြည့်ထားပါတယ်)။ ဒီ error ကြောင့် ကျန်နေတဲ့ switch အားလုံးကို ကိုယ့်အတွက် အလိုအလျောက် ရှာပေးတာပါ။

လက်တွေ့ project တွေမှာ

လက်တွေ့ project တွေမှာ sealed type နဲ့ error handling ကို ဘယ်မှာ တွေ့ရလဲ

App တွေမှာ network call တစ်ခုက loading, data, error သုံးမျိုးရှိတာကို sealed type တစ်ခုနဲ့ ဖော်ပြပြီး UI က switch နဲ့ တစ်မျိုးချင်း ဆွဲပါတယ်။ ဒါကြောင့် state အသစ် (ဥပမာ empty) ထပ်ထည့်တဲ့အခါ compiler က မပြင်ရသေးတဲ့ screen တိုင်းကို ပြပေးပါတယ်။ Error handling ကတော့ အလွှာတစ်ခုချင်းမှာ တာဝန်ရှိတဲ့ အပိုင်းကိုပဲ ဖမ်းဖို့ ပိုအရေးကြီးပါတယ်။

  • API layer: http failure ကို ကိုယ်ပိုင် sealed failure type (NetworkFailure, NotFound, ServerError) အဖြစ် ပြောင်းပေးပြီး UI က package ရဲ့ exception type ကို မသိစေဘဲ switch နဲ့ ကိုင်ပါတယ်။
  • Input parsing: JSON, form input စတာကို int.tryParse ဒါမှမဟုတ် Result ပြန်တဲ့ function တွေနဲ့ ကိုင်ပြီး ပုံမှန် failure အတွက် exception မသုံးတာက ပိုရှင်းပါတယ်။
  • Logging နဲ့ crash reporting: catch (e, st) နဲ့ ထိပ်ဆုံးမှာ error နဲ့ stack trace ကို မှတ်တမ်းတင်ပြီး မမျှော်လင့်တဲ့ Error တွေကို ပြန်ပစ်ပါတယ်။

အမှားများ

Sealed type နဲ့ error handling မှာ ဖြစ်လေ့ရှိတဲ့ အမှားများ

catch (e) နဲ့ အားလုံးကို ဖမ်းပြီး ဖုံးထားခြင်း

try { ... } catch (e) { } က FormatException နဲ့အတူ RangeError, StateError လို bug တွေကိုပါ ဖမ်းပစ်လို့ ပျက်စီးတာကို မတွေ့တော့ပါဘူး။ on FormatException catch (e) လို့ ကိုင်ချင်တဲ့ type ကိုပဲ ဖော်ပြပါ၊ မဖော်ပြတဲ့ ကျန်တာက ဆက်တက်သွားပါစေ။

ပုံမှန်ရလဒ်အတွက် exception ကို control flow အဖြစ် သုံးခြင်း

try { int.parse(text) } on FormatException { ... } ဟာ text မှားတာ ပုံမှန်ဖြစ်နိုင်တဲ့အခါ အလုပ်များပါတယ်။ int.tryParse(text) က null ပေးတာ ဒါမှမဟုတ် Result ပြန်တာက ပိုတိုပြီး ခေါ်သူကိုလည်း အခြေအနေ နှစ်ခုလုံး ကိုင်ဖို့ တွန်းပါတယ်။

Exception မဟုတ်တဲ့ object ကို throw လုပ်ခြင်း

throw 'out of stock'; က compile ဖြစ်ပါတယ်၊ ဒါပေမဲ့ catch ဘက်မှာ on String လို့သာ ဖမ်းလို့ရပြီး အဓိပ္ပာယ်ရှိတဲ့ type မရှိတဲ့အတွက် (အပေါ်က ဥပမာမှာ other -> just a string ဖြစ်တာ တွေ့ခဲ့ပါတယ်) ဘယ်သူမှ ရွေးမဖမ်းနိုင်ပါဘူး။ class OutOfStock implements Exception လို့ ကိုယ်ပိုင် type ရေးပါ။

Cleanup ကို success path မှာပဲ ထားခြင်း

file.close() ကို try ဘလောက်ရဲ့ နောက်ဆုံး line မှာ ထားရင် အလယ်ကနေ throw ဖြစ်တဲ့အခါ မ run တော့ဘဲ resource ပေါက်ကြားပါတယ်။ cleanup ကို finally ထဲ ထည့်ပါ၊ return, throw ဖြစ်ပြီးတဲ့အခါပါ အမြဲ run ပါတယ်။

Best Practices

Best practices

  • Sealed type ကို switch လုပ်ရင် _ မထည့်ပါနဲ့၊ subtype အသစ်ထပ်လာရင် compiler က သတိပေးတာကို ဆက်ရချင်လို့ပါ။
  • Custom exception ကို implements Exception နဲ့ ရေးပြီး ကိုင်တွယ်သူအတွက် လိုတဲ့ field (input, reason) တွေကို ထည့်ပါ၊ toString ကိုလည်း ရှင်းရှင်းရေးပါ။
  • on ကိုသုံးပြီး ကိုယ်ကိုင်နိုင်တဲ့ type ကိုပဲ ဖမ်းပါ၊ catch (e) ကို ထိပ်ဆုံး logging အတွက်ပဲ ထားပါ။
  • Resource ကို ပြန်လွှတ်တာကို finally မှာ ထားပြီး rethrow ကို သုံးပါ၊ throw e လို့ ပြန်မပစ်ပါနဲ့။

Mini challenge

Mini challenge: ငွေထုတ်ယူမှု ရလဒ်

ငွေထုတ်တဲ့ function တစ်ခုကို ရေးပါ။ ပမာဏက 0 ဒါမှမဟုတ် အနုတ်ဆိုရင် ArgumentError (bug)၊ လက်ကျန်မလောက်ရင် ကိုယ်ပိုင် InsufficientFunds exception ကို throw ပါ။ tryWithdraw က InsufficientFunds ကိုပဲ ဖမ်းပြီး sealed type WithdrawResult (Done ဒါမှမဟုတ် Refused) အဖြစ် ပြောင်းပေးရမယ်၊ ArgumentError ကို မဖမ်းဘဲ ဆက်တက်စေရပါမယ်။

  • InsufficientFunds က Exception ကို implements လုပ်ပြီး shortBy field ရှိရမယ်
  • withdraw(balance, amount) က amount <= 0 ဆိုရင် ArgumentError.value၊ လက်ကျန်မလောက်ရင် InsufficientFunds ကို throw ပြီး မဟုတ်ရင် လက်ကျန်အသစ်ကို ပြန်ရမယ်
  • sealed class WithdrawResult မှာ Done(balance) နဲ့ Refused(reason) ရှိပြီး tryWithdraw က InsufficientFunds ကိုပဲ ဖမ်းကာ finally ထဲမှာ attempt အရေအတွက် တိုးရမယ်
  • show က exhaustive switch expression ဖြစ်ရမယ်၊ main မှာ -5 နဲ့ ခေါ်ရင် ArgumentError ကို သီးခြား ဖမ်းပြပါ
withdrawals.dart
// TODO 1: class InsufficientFunds implements Exception, with a `shortBy` field

// TODO 2: double withdraw(double balance, double amount)
//         - amount <= 0 is a bug: throw ArgumentError.value(...)
//         - amount > balance: throw InsufficientFunds(amount - balance)
//         - otherwise return the new balance

// TODO 3: sealed class WithdrawResult with Done(balance) and Refused(reason)

var attempts = 0;

// TODO 4: WithdrawResult tryWithdraw(double balance, double amount)
//         catch ONLY InsufficientFunds; count every call in finally

// TODO 5: String show(WithdrawResult r) as an exhaustive switch expression

void main() {
  // TODO 6: withdraw 30 from 100, then 150 from 100, then -5 from 100;
  //         catch the ArgumentError from the last call and print its message,
  //         then print how many attempts were made
}

ရလဒ်: Run လိုက်ရင် ဒီလို print ထွက်ရပါမယ်: Done: 70.0 Refused: need 50.0 more bug caught: must be positive attempts: 3

အရိပ်အမြွက် ကြည့်ရန်

tryWithdraw ထဲမှာ try { return Done(withdraw(...)); } on InsufficientFunds catch (e) { return Refused('need ${e.shortBy} more'); } finally { attempts++; } လို့ ဖွဲ့ပါ။ ArgumentError ကို on clause မရေးထားလို့ ကျော်ပြီး main ထိ တက်ပါလိမ့်မယ်၊ ဒါပေမဲ့ finally က အဲဒီအခါလည်း run လို့ attempts က ၃ ဖြစ်ပါတယ်။ ArgumentError.value(amount, 'amount', 'must be positive') ရဲ့ message က 'must be positive' ပါ။

အဖြေ ကြည့်ရန်
withdrawals.dart
class InsufficientFunds implements Exception {
  InsufficientFunds(this.shortBy);

  final double shortBy;

  @override
  String toString() => 'InsufficientFunds(short by $shortBy)';
}

double withdraw(double balance, double amount) {
  if (amount <= 0) {
    throw ArgumentError.value(amount, 'amount', 'must be positive');
  }
  if (amount > balance) throw InsufficientFunds(amount - balance);
  return balance - amount;
}

sealed class WithdrawResult {}

class Done extends WithdrawResult {
  Done(this.balance);

  final double balance;
}

class Refused extends WithdrawResult {
  Refused(this.reason);

  final String reason;
}

var attempts = 0;

WithdrawResult tryWithdraw(double balance, double amount) {
  try {
    return Done(withdraw(balance, amount));
  } on InsufficientFunds catch (e) {
    return Refused('need ${e.shortBy} more');
  } finally {
    attempts++;
  }
}

String show(WithdrawResult r) => switch (r) {
      Done(balance: var b) => 'Done: $b',
      Refused(reason: var why) => 'Refused: $why',
    };

void main() {
  print(show(tryWithdraw(100, 30)));
  print(show(tryWithdraw(100, 150)));
  try {
    tryWithdraw(100, -5);
  } on ArgumentError catch (e) {
    print('bug caught: ${e.message}');
  }
  print('attempts: $attempts');
}

Quick Quiz 1 / 3

try { <int>[1][5]; } on Exception catch (e) { print('handled'); } ကို run ရင် ဘာဖြစ်မလဲ?

Quick Quiz 2 / 3

sealed class Outcome ရဲ့ subtype က Valid နဲ့ Invalid ဖြစ်ပြီး Skipped ကို နောက်မှ ထပ်ထည့်တယ်။ switch (outcome) { Valid() => ..., Invalid() => ... } ဆိုတဲ့ switch expression မှာ _ မပါရင် ဘာဖြစ်မလဲ?

Quick Quiz 3 / 3

int f() { try { return 1; } finally { print('cleanup'); } } ရှိတယ်ဆိုပါစို့။ print(f()) က ဘာတွေ print ထုတ်မလဲ?

မှတ်ထားရမယ့် အချက်များ

  • Sealed class က subtype အစုကို ပိတ်ထားလို့ switch expression က case တိုင်းကို ကိုင်ရပြီး subtype အသစ်ထပ်လာရင် မပြင်ရသေးတဲ့ switch တိုင်းကို compile မှာ ဖမ်းပေးပါတယ်။
  • Exception က ပြန်ကောင်းနိုင်တဲ့ အခြေအနေ (implements Exception နဲ့ custom type ရေးပါ)၊ Error က bug ဖြစ်လို့ ဖုံးမထားဘဲ ပြင်သင့်ပါတယ်။
  • try/on/catch/finally မှာ on က type နဲ့ ရွေးပြီး finally က return ပြီးတဲ့အခါပါ အမြဲ run ပါတယ်၊ ပြန်ပစ်ချင်ရင် throw e အစား rethrow သုံးပါ။
  • မအောင်မြင်မှုက ပုံမှန်ရလဒ်ဆိုရင် Result<T> လို sealed type ကို၊ မမျှော်လင့်တဲ့ အခြေအနေဆိုရင် exception ကို ရွေးပါ။

Dart class modifiers — Dart

နောက်ဆုံးပြင်ဆင်ရက်

Progress ကို ဤ browser (ဤစက်) တွင်သာ သိမ်းထားပါသည်။ အခြားစက်များနှင့် sync မလုပ်ပါ။

ဤသင်ခန်းစာတွင် အမှားတွေ့ပါက အကြောင်းကြားရန်သင့် email app ကို ဤသင်ခန်းစာလိပ်စာ ဖြည့်ပြီးသားဖြင့် ဖွင့်ပေးပါမည် — သင်ကိုယ်တိုင် ပို့မှသာ ပို့မည်ဖြစ်သည်။

Sealed Types & Error Handling | Thuta Learning