如何创建一个自定义异常,并处理它在省道

我编写这段代码是为了测试 Dart 中自定义异常是如何工作的。

我没有得到想要的输出,有人能给我解释一下怎么处理吗?

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

}


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

You can look at the Exception part of A Tour of the Dart Language.

The following code works as expected (custom exception has been obtained is displayed in console) :

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

You don't need an Exception class if you don't care about the type of Exception. Simply fire an exception like this:

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

You can also create an abstract exception.

Inspiration taken from TimeoutException of async package (read the code on Dart API and 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);
}

Try this Simple Custom Exception Example for Beginners

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