想要强制使用权限和“快速失败”——一些旧的 API 会悄无声息地失败 IIRC——所以我想出了:
private static void assertPermission(Context ctx, String perm) {
final int checkPermission = ctx.getPackageManager().checkPermission(
perm, ctx.getPackageName());
if (checkPermission != PackageManager.PERMISSION_GRANTED) {
throw new IllegalStateException("Permission " + perm
+ " is required");
}
}
我想使用适合抽象的权限 - 并遵循有效的 Java 建议:支持使用标准异常。
- 我应该使用
IllegalStateException
还是有一些更合适的 异常(exception) ? - 我应该使用检查异常吗?
最佳答案
如果你想要一个通用的 Java 异常,我会使用 UnsupportedOperationException
,这是一个 RuntimeException
在尝试不支持的操作时使用。
根据文档,IllegalStateException
更多地链接到 VM 本身:
Thrown when an action is attempted at a time when the VM is not in the correct state.
关于java - 缺少 android 权限时适合抛出什么异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18897318/