无法使用 try-catch 捕获 Java (Android) 异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19000393/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 13:14:51  来源:igfitidea点击:

Can't catch Java (Android) Exception with try-catch

javaandroidsqliteexceptiontry-catch

提问by kramer65

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

我是一名 Java (Android) 初学者(来自 Python),我正在尝试使用 Try-Catch 捕获异常,如下所示:

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

09-25 10:53:32.147: E/SQLiteDatabase(7991): android.database.sqlite.SQLiteConstraintException: 错误代码 19: 约束失败

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

为什么它不捕获异常?我在这里做错了吗?欢迎所有提示!

The save() method looks as follows:

save() 方法如下所示:

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);
}

采纳答案by Biraj Zalavadia

There are two classes to catch the problems.

有两个类可以解决问题。

  1. Error
  2. Exception
  1. 错误
  2. 例外

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

两者都是Throwable类的子类。当出现我们不知道的情况时,那个特定的代码块会抛出异常还是错误?您可以使用ThrowableThrowable将同时捕获ErrorsExceptions

Do this way

这样做

try {
    u.save();
} catch (Throwable e) {
    e.printStackTrace();
}

回答by bofredo

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 -->

Log 需要某些变量名称,例如 verbose(v)、debug(d) 或 info(i)。你的“wtf”不属于那里。检查此答案以获取更多信息-->

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

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

or this:

或这个:

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

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

回答by Jitesh Dalsaniya

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

约束失败通常表示您执行了一些操作,例如将null值传递到您null在创建表时声明为 not 的列中。

回答by LMK

Try

尝试

try {
u.save();

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

回答by Mobifly

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));
}