3

This might be a basic question but I cannot find an answer. When you want to catch only FileNotFound in Android, then you write

        } catch (FileNotFoundException e)  {

But what do you write if you want to catch exactly ENOSPC (No space left on device) errors? I can't use "catch (Exception e)" because I want to explicitly deal with this one error.

Kenobi
  • 425
  • 1
  • 4
  • 19

1 Answers1

9

You cannot do so directly as enospc is signaled as a java.io.IOException which will catch many other io related issues as well. But by looking up the cause and the error it's signalling you can zoom in and handle enospc exceptions but rethrow all others, like this:

} catch (IOException ex) {
    boolean itsanenospcex = false;
    // make sure the cause is an ErrnoException
    if (ex.getCause() instanceof android.system.ErrnoException) {
        // if so, we can get to the causing errno
        int errno = ((android.system.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;
    }
}

Sidenote: } catch (Exception e) { is generally considered bad practice.

Idrizi.A
  • 9,819
  • 11
  • 47
  • 88
fvu
  • 32,488
  • 6
  • 61
  • 79
  • Thank you so much, I would have needed days to figure that out. Is there actually any recommended way to simulate this error for testing purposes (apart from filling my smartphone with data till it bursts)? – Kenobi Oct 19 '16 at 22:04
  • There's a constructor for ErrnoException that accepts an errno value so you can just `throw new ErrnoException("functionname",ENOSPC)` in your testcode - I am usure what you should put in that functionname string, but I don't think it really matters for testing purposes. – fvu Oct 19 '16 at 22:10
  • The drawback of this solution is it requires min api 21 – Vadim Shved Dec 04 '19 at 15:49