flutter 如何在dart中创建自定义异常并处理它

ecfsfe2w  于 2023-05-29  发布在  Flutter
关注(0)|答案(4)|浏览(192)

我写这段代码是为了测试自定义异常在dart中是如何工作的。
我没有得到想要的输出,有人能告诉我如何处理吗??

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

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

1u4esq0p1#

您可以查看 A Tour of the Dart Language 中的异常部分。
以下代码按预期工作(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');
}
ar7v8xwq

ar7v8xwq2#

如果你不需要具体的问题,你可以抛出一个一般性的问题,像这样:

throw ("This is my first general exception");

但最好尽可能使用特定错误。他们会告诉你更多的错误,这样你就可以找出如何修复它。

vecaoik1

vecaoik13#

您也可以创建一个抽象异常。

  • 灵感来自async包的TimeoutException(阅读Dart API和Dart SDK上的代码)。*
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);
}
ig9co6j1

ig9co6j14#

尝试这个简单的自定义异常示例

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

相关问题