为什么在 dart 的 catch 语句中定义捕获异常的类型时会收到此错误?

我在玩 dart 语法

我正在尝试这个代码:

WebDriverWait

我得到的错误信息是

void main() {
  print("Hello to demo");

  try{
    throw Test("hello");
  }
  on Test catch(Test e,StackTrace s){ //error on this line 
    print("error message is ${(e).message}");
  }
}

class Test{

  String? message;

  Test(this.message);
}

我知道 dart 是强类型语言,但同时显式定义类型是可选的,但我不知道为什么我会在这里收到此消息,是否存在某些情况(例如此处的 'catch' must be followed by '(identifier)' or '(identifier,identifier)'. No types are needed,the first is given by 'on',the second is always 'StackTrace' )甚至指定类型是被禁止的,甚至不是可选的?

ps:我正在阅读文档 here

guotenglin534577320 回答:为什么在 dart 的 catch 语句中定义捕获异常的类型时会收到此错误?

简单地说,catch 是一个关键字,而不是一个函数,它的设计方式是您无法设置参数类型。您必须将其用作 documented here,例如:

try {
  // ···
} on Exception catch (e) {
  print('Exception details:\n $e');
} catch (e,s) {
  print('Exception details:\n $e');
  print('Stack trace:\n $s');
}

您的代码是这样工作的:

void main() { 
   print("Hello to demo");
   try { 
      throw Test("hello"); 
   } 
   on Test catch(e,s){ 
    print("error message is ${(e).message}");
    print("stacktrace is ${(s)}");
  }

} 
class Test {
   String? message; 
   Test(this.message);
}  
本文链接:https://www.f2er.com/7342.html

大家都在问