英文:
How to access custom exception class members when using catch(e)? And why exactly am I getting this error?
问题
如何在捕获自定义异常类的异常后访问其成员变量?为什么尽管runtimeType显示它是customException类型而不是Object类型,我们还会收到此错误?
class CustomException implements Exception {
// 自定义异常类
String message;
int numberMessage;
CustomException(this.message, this.numberMessage);
@override
String toString() {
return message;
}
}
void main() {
try {
throw CustomException('这是最好的', 1223);
} catch (z, t) {
print(z);
print(z.runtimeType); // 打印 'CustomException'
print(z.numberMessage); // 我如何访问这个成员?显示错误 'the getter ...numberMessage isn't defined for class Object'.
print(t.runtimeType); // 打印 _StackTrace
}
}
我尝试在catch关键字中添加类型为CustomException,如下所示,但即使这样也无法工作,因为这是错误的语法。
catch (CustomException z, t)
英文:
How to access a custom exception class's member variable after we catch it in a catch argument?
And why exactly are we getting this error although the runtimeType shows that it is of type customException and not Object?
class CustomException implements Exception{
//Custom Exception class
String message;
int numberMessage;
CustomException(this.message, this.numberMessage);
@override
String toString() {
return message;
}
}
void main() {
try {
throw CustomException('This is the best', 1223);
} catch (z,t) {
print(z);
print(z.runtimeType); //Prints 'CustomException'
print(z.numberMessage); //How do I access this member? Shows an error 'the getter
//...numberMessage isn't defined for class Object'.
print(t.runtimeType);//Prints _StackTrace
}
}
I tried adding the type as CustomException in the catch keyword like so, but even this didn't work as it is a wrong syntax.
catch(CustomException z, t)
答案1
得分: 0
以下是您要翻译的内容:
在catch块中捕获特定类型的异常的关键字是,您可以像下面这样使用 -
void main() {
try {
throw CustomException('This is the best', 1223);
} on CustomException catch (z, t) {
print(z);
print(z.runtimeType); // 打印 'CustomException'
print(z.numberMessage); // 如何访问此成员?显示错误 'the getter
//...numberMessage isn't defined for class Object'.
print(t.runtimeType);// 打印 _StackTrace
}
}
英文:
There is on keyword to catch particular type of exception in catch block, you can use that like below -
void main() {
try {
throw CustomException('This is the best', 1223);
} on CustomException catch (z,t) {
print(z);
print(z.runtimeType); //Prints 'CustomException'
print(z.numberMessage); //How do I access this member? Shows an error 'the getter
//...numberMessage isn't defined for class Object'.
print(t.runtimeType);//Prints _StackTrace
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论