在Android上只捕获ENOSPC

Ken*_*obi 2 error-handling android

这可能是一个基本问题,但我找不到答案.如果你想在Android中只捕获FileNotFound,那么你就写了

        } catch (FileNotFoundException e)  {
Run Code Online (Sandbox Code Playgroud)

但是如果你想要准确地捕获ENOSPC(设备上没有空间)错误,你会怎么写?我不能使用"catch(Exception e)"因为我想明确处理这一个错误.

fvu*_*fvu 7

你不能直接这样做,因为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;
    }
}
Run Code Online (Sandbox Code Playgroud)

旁注:} catch (Exception e) {通常被认为是不好的做法.