2
\$\begingroup\$

Here is code that retrieves an access token from SharedPreference.

  public static AuthToken getFromPreference(SharedPreferences p) {
    try {
      String at = p.getString(ACCESS_TOKEN_KEY, "");
      String uid = p.getString(USER_ID_KEY, "");
      long t = p.getLong(EXPIRES_AT_KEY, -1);

      if (at.isEmpty() || uid.isEmpty() || t == -1)
        return null;

      return new AuthToken(at, uid, t);
    } catch (ClassCastException e) {
      Log.wtf(TAG, "Incorrect field type in shared preference.");
      return null;
    }
  }

Can I omit exception handling if I don't expect it to happen in normal workcycle? Or should I handle even this terrible situation to not let app crash?

\$\endgroup\$
2
\$\begingroup\$

ClassCastException is not a checked exception, and so it's not a normal practice to catch it. You can omit catching this exception. However, you should make sure your application will never store values in shared preferences that would raise such errors.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.