为什么在 dart 的 catch 语句中定义捕获异常的类型时会出现此错误?
Why am I getting this error while defining the types of the caught exceptions in the catch statement in dart?
我在玩 dart 语法
我正在尝试这段代码:
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);
}
我收到的错误信息是
'catch' must be followed by '(identifier)' or '(identifier, identifier)'.
No types are needed, the first is given by 'on', the second is always 'StackTrace'
我知道 dart 是强类型语言,但同时显式定义类型是可选的,但我不知道为什么我会在这里收到此消息,是否存在某些情况(例如 catch
这里) 甚至指定类型都是禁止的,甚至不是可选的?
p.s.: 我正在阅读文档 here
简单地说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);
}
我在玩 dart 语法
我正在尝试这段代码:
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);
}
我收到的错误信息是
'catch' must be followed by '(identifier)' or '(identifier, identifier)'.
No types are needed, the first is given by 'on', the second is always 'StackTrace'
我知道 dart 是强类型语言,但同时显式定义类型是可选的,但我不知道为什么我会在这里收到此消息,是否存在某些情况(例如 catch
这里) 甚至指定类型都是禁止的,甚至不是可选的?
p.s.: 我正在阅读文档 here
简单地说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);
}