1

In android, I have the following error thrown:

java.lang.NoSuchFieldError: android.os.Build.SERIAL

It happens only on certain devices, for instance: "sec_smdk6410" or "sdkDemo".

I have tried to catch the exception but it ignores the try/catch block.

    try {
        return android.os.Build.SERIAL;
    } catch (Exception e) {
        return null;
    }

Is there anyway I can detect if this error will be thrown in order to adapt my code ?

Thanks.

Joel
  • 3,427
  • 5
  • 38
  • 60

2 Answers2

6

The documentation states it is only available for API level 9. You could check the API level by using:

if(Build.VERSION.SDK_INT >= 9)
    // safe to use 
else
   // ignore

Untested, but I would give it a go

Entreco
  • 12,738
  • 8
  • 75
  • 95
  • 1
    Just a heads up but this version check only works if you are running on a device **API > 4**. If the device is API level 4 or lower (donut or lower) then the app will crash with a [`VerifyError`](http://developer.android.com/reference/java/lang/VerifyError.html). The reason is because there was a change starting with Android 2.0 to the way the Dalvik VM loads classes until it actually uses them. See here: http://stackoverflow.com/a/7265487/708906 – Tony Chan Jun 05 '13 at 01:55
0

The NoSuchFieldError is not an Exception, it's an Error (that's why it was not being catched in your code).

Both Errors and Exceptions are Throwables. That means Errors can also be catched:

try {
    return android.os.Build.SERIAL;
} catch (NoSuchFieldError e) { //Notice the change here
    return null;
}

More on the "Differences between Exception and Error".

orlandocr
  • 313
  • 2
  • 8