73

このコードは、ダーツでカスタム例外がどのように機能するかをテストするために作成しました。

希望する出力が得られません。誰かがそれを処理する方法を説明してもらえますか?

void main() 
{   
  try
  {
    throwException();
  }
  on customException
  {
    print("custom exception is been obtained");
  }
  
}

throwException()
{
  throw new customException('This is my first custom exception');
}
4

5 に答える 5

126

あなたはダーツ言語のツアーの例外部分を見ることができます。

次のコードは期待どおりに機能します(custom exception has been obtainedコンソールに表示されます):

class CustomException implements Exception {
  String cause;
  CustomException(this.cause);
}

void main() {
  try {
    throwException();
  } on CustomException {
    print("custom exception has been obtained");
  }
}

throwException() {
  throw new CustomException('This is my first custom exception');
}
于 2012-11-27T08:38:22.703 に答える
44

Exceptionのタイプを気にしない場合は、Exceptionクラスは必要ありません。次のような例外を発生させるだけです。

throw ("This is my first general exception");
于 2020-01-09T10:46:49.923 に答える
17

Dartコードは、例外をスローしてキャッチできます。Javaとは対照的に、Dartのすべての例外はチェックされていない例外です。メソッドは、スローする可能性のある例外を宣言しません。また、例外をキャッチする必要はありません。

Dartは提供しExceptionErrorタイプしますが、null以外のオブジェクトをスローすることは許可されています。

throw Exception('Something bad happened.');
throw 'Waaaaaaah!';

try例外を処理するときは、、、onおよびcatchキーワードを使用します。

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');
}

tryキーワードは、他のほとんどの言語と同じように機能します。キーワードを使用しonて特定の例外をタイプでフィルタリングし、キーワードを使用catchして例外オブジェクトへの参照を取得します。

例外を完全に処理できない場合は、rethrowキーワードを使用して例外を伝播します。

try {
  breedMoreLlamas();
} catch (e) {
  print('I was just trying to breed llamas!.');
  rethrow;
}

例外がスローされるかどうかに関係なくコードを実行するには、次を使用しますfinally

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

コード例

以下に実装しtryFunction()ます。信頼できないメソッドを実行してから、次のことを実行する必要があります。

  • untrustworthy()をスローする場合は、例外タイプとメッセージを指定してExceptionWithMessage呼び出します(とを使用してみてください)。logger.logExceptiononcatch
  • untrustworthy()例外をスローする場合は、logger.logException例外タイプで呼び出します(onこれに使用してみてください)。
  • 他のオブジェクトをスローする場合untrustworthy()は、例外をキャッチしないでください。
  • すべてがキャッチされて処理されたら、呼び出しますlogger.doneLogging(を使用してみてくださいfinally)。

typedef VoidFunction = void Function();

class ExceptionWithMessage {
  final String message;
  const ExceptionWithMessage(this.message);
}

abstract class Logger {
  void logException(Type t, [String msg]);
  void doneLogging();
}

void tryFunction(VoidFunction untrustworthy, Logger logger) {
  try {
    untrustworthy();
  } on ExceptionWithMessage catch (e) {
    logger.logException(e.runtimeType, e.message);
  } on Exception {
    logger.logException(Exception);
  } finally {
    logger.doneLogging();
于 2021-01-23T02:58:40.363 に答える
0

抽象例外を作成することもできます。

パッケージから得られたインスピレーション( DartAPIおよびDartSDKのコードを読んでくださいTimeoutException)。async

abstract class IMoviesRepoException implements Exception {
  const IMoviesRepoException([this.message]);

  final String? message;

  @override
  String toString() {
    String result = 'IMoviesRepoExceptionl';
    if (message is String) return '$result: $message';
    return result;
  }
}

class TmdbMoviesRepoException extends IMoviesRepoException {
  const TmdbMoviesRepoException([String? message]) : super(message);
}
于 2021-10-12T21:19:13.580 に答える
0
    Try this Simple Custom Exception Example for Beginners 
    
   class WithdrawException implements Exception{
  String wdExpMsg()=> 'Oops! something went wrong';
}
void main() {   
   try {   
      withdrawAmt(400);
   }   
  on WithdrawException{
    WithdrawException we=WithdrawException();
    print(we.wdExpMsg());
  }
  finally{
    print('Withdraw Amount<500 is not allowed');
  }
}    
void withdrawAmt(int amt) {   
   if (amt <= 499) {   
      throw WithdrawException();   
   }else{
     print('Collect Your Amount=$amt from ATM Machine...');
   }   
}    
于 2022-02-22T06:12:03.097 に答える