Exceptions


Exceptions


意味:exceptionsは、思いがけないことが起こったことを示すエラーです.
機能:dart codeは異常を放出し、異常をキャプチャできます.
特徴:dartはexceptionとerrortypesを提供しますが、null以外のオブジェクトしか放出できません.

例外の処理に必要な用語


throw


異常が発生した場合、オブジェクトやコードなどを返すことができます.
//間違いを試してみるべきだと思います
throw使用コード例)
//example 1
throw FormatException('Expected at least 1 section');
//example 2
throw 'Out of llamas!';
example 1の使用を推奨します.
  • でエラータイプを表すimplemeterを使用することをお勧めします.
    why?
    implemeterには様々な異常とエラーがあるからです.
  • catch


    catchは,種々の異常を与えることによって,特定の場合のエラーを制御する.
    ->再び異常が発生しない限り、異常は伝播しません.
    //異常捕捉と理解
    複数のcatch文を使用して、複数のエラーを制御します.
    エラーの前にonまたはcatchを使用します.
    <サンプルコード1>
    try {
      breedMoreLlamas();
    } on OutOfLlamasException {
      buyMoreLlamas();
    }
    //OutofLiamasException이라는 오류가 생기면 buyMoreLlamas()실행.
    <サンプルコード2>
    try {
      breedMoreLlamas();
    } on OutOfLlamasException {
      // 지정해둔 특정 오류 상황(OutOfLlamas라는 오류 상황) 처리
      buyMoreLlamas();
    } on Exception catch (e) {
      // exception 타입으로 지정한 오류 처리 
      // (위에 선언한 OutOfLlamasException는 제외)
      print('Unknown exception: $e');
    } catch (e) {
      // 타입이 특정하게 지정되지 않은 나머지 오류 처리
      print('Something really unknown: $e');
    }
    //한 경우씩 위에서부터 걸러서 내려온다고 생각

    rethrow


    再送はエラーを再伝播します.再伝播は、関数のエラーを表示するためです.
    例外が完全に処理できない場合に使用します.
    <サンプルコード>
    void misbehave() {
      try {
        dynamic foo = true;
        print(foo++); // 만약 여기서 런타임 오류가 났다면
      } catch (e) { // 여기서 오류를 catch하고,
        print('misbehave() partially handled ${e.runtimeType}.');
        rethrow; // call한 함수(해당 예시에서는 main함수)가 이 오류 볼 수 있도록 재전파
      }
    }
    
    void main() {
      try {
        misbehave(); // rethrow로 위에서 찾은 에러가 재전파되어 발생.
      } catch (e) { // 에러를 catch
        print('main() finished handling ${e.runtimeType}.');
      }
    }

    finally


    finallyは、例外が発生するかどうかにかかわらず、いくつかのコードを実行するために使用されます.
    最後に大きく二つのケースに分けられます.

    1.catchがある場合


    エラーに合致するcatch文がある場合は、まずcatch文を実行し、finallyを実行します.
    実行順序:catch文->finally
    <サンプルコード>
    try {
      breedMoreLlamas();
    } catch (e) {
      print('Error: $e'); // 에러를 먼저 제어한다.
    } finally {
      cleanLlamaStalls(); // 그 다음, 함수를 실행한다.
    }

    2.catchなし


    エラーに合致するcatch文がない場合は、例外があってもfinallyを実行します.
    実行順序:finally->exception
    <サンプルコード>
    try {
      breedMoreLlamas();
    } finally {
        // 에러가 발생하더라도 아래 호출된 함수 실행
      cleanLlamaStalls();
      //catch문이 없으므로 에러가 재전파 된다.
    }

    exception code example

    typedef VoidFunction = void Function();
    
    class ExceptionWithMessage {
      final String message;
      const ExceptionWithMessage(this.message);
    }
    
    // Call logException to log an exception, and doneLogging when finished.
    abstract class Logger {
      void logException(Type t, [String? msg]);
      void doneLogging();
    }
    
    void tryFunction(VoidFunction untrustworthy, Logger logger) {
      // Invoking this method might cause an exception. Catch and handle
      // them using try-on-catch-finally.
      untrustworthy();
    }

    solution code

    typedef VoidFunction = void Function();
    
    class ExceptionWithMessage {
      final String message;
      const ExceptionWithMessage(this.message);
    }
    // Call logException to log an exception, and doneLogging when finished.
    abstract class Logger {
      void logException(Type t, [String? msg]);
      void doneLogging();
    }
    
    void tryFunction(VoidFunction untrustworthy, Logger logger) {
    // Invoking this method might cause an exception. Catch and handle
        // them using try-on-catch-finally.
      try {
        untrustworthy();
      } on ExceptionWithMessage catch (e) {
        logger.logException(e.runtimeType, e.message);
      } on Exception {
        logger.logException(Exception);
      } finally {
        logger.doneLogging();
      }
    }
    メモサイト1:https://m.blog.naver.com/mingdyuo/221803704762
    リファレンスサイト2:https://dart.dev/codelabs/dart-cheatsheet#initializer-lists