Exception Java';抛出';Dart中的关键字
我来自一个Java背景,在那里我使用throws关键字将异常引入调用另一个方法的方法。我该怎么做我的飞镖 方法调用:Exception Java';抛出';Dart中的关键字,exception,flutter,dart,throws,Exception,Flutter,Dart,Throws,我来自一个Java背景,在那里我使用throws关键字将异常引入调用另一个方法的方法。我该怎么做我的飞镖 方法调用: void _updateCurrentUserEmail() async { await FirebaseAuth.instance .currentUser() .then((FirebaseUser user) { _email = user.email; }); } 如何称呼它: try { _upd
void _updateCurrentUserEmail() async {
await FirebaseAuth.instance
.currentUser()
.then((FirebaseUser user) {
_email = user.email;
});
}
如何称呼它:
try {
_updateCurrentUserEmail();
} on Exception {
return errorScreen("No User Signed In!", barActions);
}
但似乎没有捕获到异常,因为我仍然得到一个NoSuchMethodException,并且没有显示errorScreen。将其更改为:
try {
_updateCurrentUserEmail();
} on Exception catch(e){
print('error caught: $e')
}
处理错误的另一种方法是执行以下操作:
void _updateCurrentUserEmail() async {
await FirebaseAuth.instance
.currentUser()
.then((FirebaseUser user) {
_email = user.email;
throw("some arbitrary error");
});
.catchError(handleError);
}
handleError(e) {
print('Error: ${e.toString()}');
}
如果currentUser()的未来以一个值完成,则()的回调将触发。如果then()的回调中的代码抛出(如上面的示例所示),则()的未来将以错误完成。该错误由catchError()处理
检查文档:
当您正确使用try/catch时,异常来自一个您没有等待的异步函数 try/catch仅捕获该块中抛出的异常。但既然你写了:
试试看{
dosomethingasyncthattwilltrowlater();
}捕获(e){
}
然后,异步方法引发的异常被抛出try
主体之外(正如try
在异步函数之前完成),因此不会被捕获
您的解决方案是使用等待
:
试试看{
等待dosomethingasyncthattwilltrowlater();
}捕获(e){
}
或者使用Future.catchError
/Future。然后
:
doSomethingAsyncThatWillTrowLater().catchError((错误){
打印('Error:$Error');
});
从
如果catch子句未指定类型,则该子句可以处理任何类型的抛出对象:
试试看{
繁殖的哺乳动物();
}论超性别观念{
//特定的例外
buyMoreLlamas();
}关于异常捕获(e){
//还有什么例外吗
打印('Unknown exception:$e');抛出
下面是一个抛出或引发异常的示例:
throw FormatException('Expected at least 1 section');
您还可以抛出任意对象:
throw 'Out of llamas!';
抛出异常是一个表达式,您可以在=>语句中以及允许表达式的任何其他地方抛出异常:
void someMethod(Point other) => throw UnimplementedError();
下面是一个例子
main() {
try {
test_age(-2);
}
catch(e) {
print('Age cannot be negative');
}
}
void test_age(int age) {
if(age<0) {
throw new FormatException();
}
}
main(){
试试{
测试年龄(-2);
}
第(e)款{
打印(“年龄不能为负数”);
}
}
无效测试时间(整数时间){
if(ageDart没有“throws”关键字,因为Dart中的所有异常都是未检查的异常
Java检查了在编译时检查的异常,这要求我们使用抛出的异常告诉编译器,如果这些异常不是由我们处理的
因此,您必须生成运行时异常。使用catch
捕获error@Benjamin但是我不想在调用_updateCurrentUserEmail的第二个方法中捕捉到它。我不想在方法本身中对异常做出反应,而是在调用它的方法中(如上所述)只需使用throw
在方法中抛出一个错误。否则我有点困惑。@Benjamin,你的意思是捕获异常并再次抛出它吗?Dart有一个名为rethrow
的关键字,所以你可以在捕获后再次抛出它。第二个选项很好,但我不能执行方法().catchError…抱歉,我还有一个问题。我正在生成方法中调用该方法。如果我使用第二个选项,则会在return语句之后进行更改,这将导致相同的结果。但我不能使用第二个选项,因为我无法使生成方法异步。
main() {
try {
test_age(-2);
}
catch(e) {
print('Age cannot be negative');
}
}
void test_age(int age) {
if(age<0) {
throw new FormatException();
}
}