3

How to check IOException cause on the catch?

Is e.getCause().getMessage() always returns the same string on all the android versions and devices for the same cause? Is it a good approach to check if IOException's cause is android.system.ErrnoException: write failed: ENOSPC (No space left on device) for checking if the user's device is out of space on that specific drive?

try {
    // Here I'm writing a file with OutputStream
} catch (IOException e) {
    // Check if IOException cause equals android.system.ErrnoException: write failed: ENOSPC (No space left on device)
} finally {

}
Eftekhari
  • 1,001
  • 1
  • 19
  • 37
  • 1
    Read this article: https://stackoverflow.com/questions/966296/ioexception-for-drive-full-or-out-of-space?rq=1 – Stanojkovic Jul 07 '17 at 19:47
  • Thank you. Actually, I was aware of that post and for now, I'm checking `IOException`'s cause by checking it's message. I thought maybe there is another or better to say safer (if checking message is not safe at all) approach to get the result. – Eftekhari Jul 07 '17 at 21:02

1 Answers1

2

It is not usually a good idea to rely on error messages as they might vary with OS versions. If targeting API level 21 or above, there is an elegant way to find the actual root cause of the IOException based on an error code. (ENOSPC in your case) https://developer.android.com/reference/android/system/OsConstants#ENOSPC

It may be checked like this:

catch (IOException e) {
    if (e.getCause() instanceof ErrnoException) { 
        int errorNumber = ((ErrnoException) e.getCause()).errno;
        if (errorNumber == OsConstants.ENOSPC) {
            // Out of space
        }
    }
}

errno is a public field in https://developer.android.com/reference/android/system/ErrnoException

Himanshu Likhyani
  • 4,490
  • 1
  • 33
  • 33