如何在飞镖中 运行 自定义异常时通过编译器解决错误?
How to solve error by compiler while running custom exception in dart?
我使用 visual studio 代码编写了以下代码来测试飞镖中的自定义异常。
(参考来自 YouTube 的教程)
我没有得到教程中显示的所需输出。
void main(){
try {
depositMoney(-200);
} catch (e) {
print(e.errorMessage());
} finally {
print("FINALLY")
}
}
class DepositException implements Exception {
String errorMessage() {
return "You cannot enter amount less than 0";
}
}
void depositMoney(int amount) {
if(amount < 0) {
throw new DepositException();
}
}
显示的输出是
bin/code18.dart:6:17: Error: The method 'errorMessage' isn't defined for the class 'Object'.
- 'Object' is from 'dart:core'.
Try correcting the name to the name of an existing method, or defining a method named 'errorMessage'.
print(e.errorMessage());
请帮我解决这个问题
...
期望的输出:
You cannot enter amount less than 0
FINALLY
我也试过了。我在初始化 catch 块时通过提及自定义异常 class 解决了这个问题。
找到下面的代码片段:
void main(){
try {
depositMoney(-200);
} on DepositException catch (e) {
print(e.errorMessage());
} finally {
print("FINALLY");
}
}
class DepositException implements Exception {
String errorMessage() {
return "You cannot enter amount less than 0";
}
}
void depositMoney(int amount) {
if(amount < 0) {
throw new DepositException();
}
}
我使用 visual studio 代码编写了以下代码来测试飞镖中的自定义异常。
(参考来自 YouTube 的教程)
我没有得到教程中显示的所需输出。
void main(){
try {
depositMoney(-200);
} catch (e) {
print(e.errorMessage());
} finally {
print("FINALLY")
}
}
class DepositException implements Exception {
String errorMessage() {
return "You cannot enter amount less than 0";
}
}
void depositMoney(int amount) {
if(amount < 0) {
throw new DepositException();
}
}
显示的输出是
bin/code18.dart:6:17: Error: The method 'errorMessage' isn't defined for the class 'Object'.
- 'Object' is from 'dart:core'.
Try correcting the name to the name of an existing method, or defining a method named 'errorMessage'.
print(e.errorMessage());
请帮我解决这个问题
...
期望的输出:
You cannot enter amount less than 0
FINALLY
我也试过了。我在初始化 catch 块时通过提及自定义异常 class 解决了这个问题。
找到下面的代码片段:
void main(){
try {
depositMoney(-200);
} on DepositException catch (e) {
print(e.errorMessage());
} finally {
print("FINALLY");
}
}
class DepositException implements Exception {
String errorMessage() {
return "You cannot enter amount less than 0";
}
}
void depositMoney(int amount) {
if(amount < 0) {
throw new DepositException();
}
}