6

I'm a Java (Android) beginner (coming from Python) and I'm trying to catch an exception using Try-Catch as follows:

try {
    u.save();
} catch (Exception e) {
    Log.wtf("DO THIS", " WHEN SAVE() FAILS");
}

To my surprise I don't see my Log message but I still get the following error:

09-25 10:53:32.147: E/SQLiteDatabase(7991): android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed

Why doesn't it catch the Exception? Am I doing something wrong here? All tips are welcome!

The save() method looks as follows:

public final void save() {
    final SQLiteDatabase db = Cache.openDatabase();
    final ContentValues values = new ContentValues();

    for (Field field : mTableInfo.getFields()) {
        final String fieldName = mTableInfo.getColumnName(field);
        Class<?> fieldType = field.getType();

        field.setAccessible(true);

        try {
            Object value = field.get(this);

            if (value != null) {
                final TypeSerializer typeSerializer = Cache.getParserForType(fieldType);
                if (typeSerializer != null) {
                    // serialize data
                    value = typeSerializer.serialize(value);
                    // set new object type
                    if (value != null) {
                        fieldType = value.getClass();
                        // check that the serializer returned what it promised
                        if (!fieldType.equals(typeSerializer.getSerializedType())) {
                            Log.w(String.format("TypeSerializer returned wrong type: expected a %s but got a %s",
                                    typeSerializer.getSerializedType(), fieldType));
                        }
                    }
                }
            }

            // TODO: Find a smarter way to do this? This if block is necessary because we
            // can't know the type until runtime.
            if (value == null) {
                values.putNull(fieldName);
            }
            else if (fieldType.equals(Byte.class) || fieldType.equals(byte.class)) {
                values.put(fieldName, (Byte) value);
            }
            else if (fieldType.equals(Short.class) || fieldType.equals(short.class)) {
                values.put(fieldName, (Short) value);
            }
            else if (fieldType.equals(Integer.class) || fieldType.equals(int.class)) {
                values.put(fieldName, (Integer) value);
            }
            else if (fieldType.equals(Long.class) || fieldType.equals(long.class)) {
                values.put(fieldName, (Long) value);
            }
            else if (fieldType.equals(Float.class) || fieldType.equals(float.class)) {
                values.put(fieldName, (Float) value);
            }
            else if (fieldType.equals(Double.class) || fieldType.equals(double.class)) {
                values.put(fieldName, (Double) value);
            }
            else if (fieldType.equals(Boolean.class) || fieldType.equals(boolean.class)) {
                values.put(fieldName, (Boolean) value);
            }
            else if (fieldType.equals(Character.class) || fieldType.equals(char.class)) {
                values.put(fieldName, value.toString());
            }
            else if (fieldType.equals(String.class)) {
                values.put(fieldName, value.toString());
            }
            else if (fieldType.equals(Byte[].class) || fieldType.equals(byte[].class)) {
                values.put(fieldName, (byte[]) value);
            }
            else if (ReflectionUtils.isModel(fieldType)) {
                values.put(fieldName, ((Model) value).getId());
            }
            else if (ReflectionUtils.isSubclassOf(fieldType, Enum.class)) {
                values.put(fieldName, ((Enum<?>) value).name());
            }
        }
        catch (IllegalArgumentException e) {
            Log.e(e.getClass().getName(), e);
        }
        catch (IllegalAccessException e) {
            Log.e(e.getClass().getName(), e);
        }
    }

    if (mId == null) {
        mId = db.insert(mTableInfo.getTableName(), null, values);
    }
    else {
        db.update(mTableInfo.getTableName(), values, "Id=" + mId, null);
    }

    Cache.getContext().getContentResolver()
            .notifyChange(ContentProvider.createUri(mTableInfo.getType(), mId), null);
}
10
  • Did you see your log message as well? Commented Sep 25, 2013 at 9:00
  • @Henry - No I don't see the error message at all. (added it to my question). Commented Sep 25, 2013 at 9:03
  • Try replacing "wtf" with "e" - you should then see your message. There is nothing wrong with your try/catch. Unless the u.save method already catches the exception and handles it Commented Sep 25, 2013 at 9:03
  • Can you show us the save method? Commented Sep 25, 2013 at 9:05
  • may be the exception is getting caught inside your save method Commented Sep 25, 2013 at 9:08

5 Answers 5

14

There are two classes to catch the problems.

  1. Error
  2. Exception

Both are sub-class of Throwable class. When there is situation we do not know, that particular code block will throw Exception or Error? You can use Throwable. Throwable will catch both Errors & Exceptions.

Do this way

try {
    u.save();
} catch (Throwable e) {
    e.printStackTrace();
}
Sign up to request clarification or add additional context in comments.

4 Comments

This gives the strange result that it doesn't show the SQLException, but it also doesn't show the Log message.. :S
It makes perfect sense + this just saved my day Thank you!
Tip: if you're getting "java.lang.NullPointerException" in your code, use the "printStackTrace()" method above, just like the example. It will cast a light over your problems.
it wont help still my app is crashing when i try to get spinner value
1

Constraint failed usually indicates that you did something like pass a null value into a column that you declare as not null when you create your table.

2 Comments

That's absolutely true. I am doing it on purpose because I want to cath this mistake when it occurs..
This answer is indeed usefull, but it doesn't solve my question. If you see the save() method, would you know how to catch the error?
1

do this way

try {
    // do some thing which you want in try block
} catch (JSONException e) {
    e.printStackTrace();
    Log.e("Catch block", Log.getStackTraceString(e));
} 

Comments

0

Try

try {
u.save();

} catch (SQLException sqle) {
Log.wtf("DO THIS", " WHEN SAVE() FAILS");
}catch (Exception e) {
Log.wtf("DO THIS", " WHEN SAVE() FAILS");
}

Comments

-2

Log is expecting certain variable-names like verbose(v), debug(d) or info(i). Your "wtf" doesnt belong there. Check this answer for more info -->

https://stackoverflow.com/a/10006054/2074990

or this:

http://developer.android.com/tools/debugging/debugging-log.html

2 Comments

Although not often used, wtf is definitely a valid variable name. Check it here: developer.android.com/reference/android/util/Log.html
LOL! now that is funny :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.