这可能是一个基本问题,但我找不到答案。如果您只想在Android中捕获FileNotFound,那么您可以编写
} catch (FileNotFoundException e) {
但是如果你想要准确捕捉ENOSPC(设备上没有剩余空间)错误,你会怎么写?我无法使用" catch(例外e)"因为我想明确处理这一个错误。
答案 0 :(得分:6)
你不能直接这样做,因为enospc被标记为java.io.IOException
,它也将捕获许多其他io相关问题。但通过查找原因和错误信号,您可以放大并处理enospc异常但重新抛出所有其他异常,如下所示:
} catch (IOException ex) {
boolean itsanenospcex = false;
// make sure the cause is an ErrnoException
if (ex.getCause() instanceof libcore.io.ErrnoException) {
// if so, we can get to the causing errno
int errno = ((libcore.io.ErrnoException)ex.getCause()).errno;
// and check for the appropriate value
itsanenospcex = errno == OSConstants.ENOSPC;
}
if (itsanenospcex) {
// handle it
} else {
// if it's any other ioexception, rethrow it
throw ex;
}
}
旁注:} catch (Exception e) {
为generally considered bad practice。