飞镖尝试抓住,抓住不射击

时间:2019-06-28 08:43:55

标签: flutter dart

给出以下简短代码示例:

    ...
    print("1 parsing stuff");
     List<dynamic> subjectjson;
    try { 
      subjectjson = json.decode(response.body);
    } on Exception catch (_) {
      print("throwing new error");
      throw Exception("Error on server");
    }
    print("2 parsing stuff");
    ...

我希望在解码失败时执行catch块。但是,当返回错误响应时,终端将显示异常,并且不会触发catch或继续代码。

flutter: 1 parsing stuff
[VERBOSE-2:ui_dart_state.cc(148)] Unhandled Exception: type 
'_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 
'List<dynamic>'

我在这里想念什么?

约翰。

7 个答案:

答案 0 :(得分:4)

您的示例中的try / catch是同步的,而异常是异步引发的。如果将函数标记为异步并等待将来返回,则可以按预期捕获异常:

Future<http.Response> foo(url, headers) async {
  try {
    return await http.get(url, headers: headers);
  } catch (e) {
    print(e);
    return null;
  }
}

答案 1 :(得分:3)

函数可以抛出任何东西,即使不是Exception的东西也可以抛出:

void foo() {
  throw 42;
}

但是on Exception子句意味着您正在专门捕获Exception 个子类。

因此,在以下代码中:

try {
  throw 42;
} on Exception catch (_) {
  print('never reached');
}

on Exception将永远不会到达。

答案 2 :(得分:2)

规则是异常处理应该从详细异常一般异常,以使操作落入正确的捕获阻止并为您提供有关错误的更多信息,例如以下方法中的 catch 块:

Future<int> updateUserById(int userIdForUpdate, String newName) async {
    final db = await database;
    try {
      int code = await db.update('tbl_user', {'name': newName}, 
          whereArgs: [userIdForUpdate], where: "id = ?");
      return code;
    } 
    on DatabaseException catch(de){
      print(de);
      return 2;
    }
    on FormatException catch(fe){
      print(fe);
      return 2;
    }
    on Exception catch(e){
      print(e);
      return 2;
    }
  }

答案 3 :(得分:1)

on Exception catch作为其他人回答不是语法错误。但是,您需要注意,除非抛出的错误类型为Exception,否则不会触发捕获。

如果要找出要获取的错误的确切类型,请删除on Exception,以便捕获所有错误,在捕获中放置一个断点并检查错误的类型。如果要为“异常”做一些事情,而为所有其他类型的错误做其他事情,则也可以使用类似于以下代码的代码:

try {
  ...
} on Exception catch (exception) {
  ... // only executed if error is of type Exception
} catch (error) {
  ... // executed for errors of all types other than Exception
}

答案 4 :(得分:1)

正如每个人或大多数人所说的,试着确切地知道你遇到了什么错误!

try{}
catch(err){
print(err.runTimeType);
}

runTimeType 将为您提供您正在获取的数据或异常的类型,或者将异常本身简单化! 然后做任何你想做的事!(比如如果你没有得到你期望的例外,那么尝试解决这个问题或改变例外)

另一种选择是使用一般形式! 使用简单的catch,每次都会提示!

答案 5 :(得分:0)

    print("1 parsing stuff");
    List<dynamic> subjectjson;
    try { 
      subjectjson = json.decode(response.body);
    } catch (_) { .   // <-- removing the on Exception clause
      print("throwing new error");
      throw Exception("Error on server");
    }
    print("2 parsing stuff");
    ...

这可行,但是背后的原理是什么?类型不一致不是异常吗?

答案 6 :(得分:0)

enter image description here

Dexter.withContext(activity)
            .withPermissions(
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION
            )
            .withListener(new MultiplePermissionsListener() {
                @SuppressLint("MissingPermission")
                @Override
                public void onPermissionsChecked(MultiplePermissionsReport report) {
                }

                @Override
                public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
                    token.continuePermissionRequest();
                }
            })
            .check();