如何创建自定义异常并在dart中进行处理



我编写了这段代码来测试自定义异常在dart中的工作方式。

我没有得到想要的输出,有人能向我解释一下如何处理吗??

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

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

您可以查看飞镖语言之旅的异常部分。

以下代码按预期工作(控制台中显示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');
}

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

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

但最好尽可能使用特定的错误。他们会告诉你更多关于哪里出了问题,这样你就可以想办法解决它

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

灵感来自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);
}

为初学者尝试这个简单的自定义异常示例

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

最新更新