避免在 Android 上尝试/捕获

发布于 2024-10-10 06:48:18 字数 348 浏览 0 评论 0原文

我是 Android 环境的新手,我已经开始编写一些代码来对数据库执行一些查询。当我必须处理异常时,我不知道正确的方法是什么 - 在 Android 中,我曾经在方法上使用 throws 声明,但似乎 throws安卓不允许吗?只是try-catch? 我这么说是因为eclipse不建议我像脱离Android环境时那样添加throws声明,我猜它与extends Activity有关。 那么android中处理异常的合适方法是什么呢?用 try-catch 包围每个句子使我的代码看起来很糟糕,而这并不是我真正想要做的。

I am new in Android environment and I have started writing some code to execute some queries on a database. When I have to handle exceptions I don't know what the appropriate way is to do it - out of Android I used to use throws declaration on methods but it seems that throws isn't allowed in android? Just try-catch?
I say this because eclipse doesn't suggest me adding throws declaration like when I am out of Android environment, I guess that it is related to extends Activity.
So what is the appropriate way to handle exceptions in android? Surrounding every sentence with try-catch makes my code look terrible and that's not really what I want to do.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

撑一把青伞 2024-10-17 06:48:18

如果您使用的方法已经抛出异常,您可能只想将异常重新抛出为新类型:

public void someMethod() throws IOException {
    try {
        //  Do database operation
    } catch (MyException e){
        throw new IOException(e.toString());
    }
}

//  Or, if there is no exception, use an unchecked exception:

public void otherMethod() {
    try {
        // DB operation
    } catch (MyException e){
        throw new RuntimeException(e);
    }
}

另一个选项是使 MyException 扩展 RuntimeException。然后编译器不会强迫您捕获它或将其添加到方法签名中。 RuntimeExceptions 被称为未经检查的异常,这意味着您不必通过 try/catch 的方式检查它们是否发生。例如 NullPointerArrayOutOfBounds

If the method you are using already throws an exception, you may want to just re-throw the exception as the new type:

public void someMethod() throws IOException {
    try {
        //  Do database operation
    } catch (MyException e){
        throw new IOException(e.toString());
    }
}

//  Or, if there is no exception, use an unchecked exception:

public void otherMethod() {
    try {
        // DB operation
    } catch (MyException e){
        throw new RuntimeException(e);
    }
}

The other option is to make MyException extend RuntimeException. Then the compiler won't force you to catch it or add it to the method signature. RuntimeExceptions are known as unchecked exceptions meaning you don't have to check for them occurring by way of a try/catch. Examples of these are NullPointer and ArrayOutOfBounds.

擦肩而过的背影 2024-10-17 06:48:18

我只是想知道 Android 环境中“抛出”的一些奇怪处理,并在这里发现了这个老问题。
提问者Jon“开始编写一些代码来在数据库上执行一些查询”,所以也许他和我注意到的一样。

编译不会出现错误:

public void onCreate(SQLiteDatabase db)
{
    db.execSQL(DbMeta.T_DISGUISED.T_CREATE);
}

尽管有这样的声明(在 javadoc 弹出窗口中):

void android.database.sqlite.SQLiteDatabase.execSQL(String sql) throws SQLException

因此,首先,monkjack 指出 onCreate 方法的签名不能通过继承实现来更改,这是正确的。
其次,Zeki 正确地指出了已检查异常和未检查异常之间的区别。

现在第三,我想补充一点,最大的混乱是由 SQLException 引起的。

上面示例中使用的 SQLException 是 Android 类型 android.database.SQLException 并继承 java.lang.RuntimeException - 它是一个未经检查的异常!无需抛出声明!

这不是经典的 java.sql.SQLException - 它是 java.lang.Exception 并且需要 try/catch/throws。

I just was wondering about some strange handling of "throws" in Android environment and found this old question here.
Asker Jon "started writing some code to execute some querys on a database", so maybe he noticed the same as I did.

This compiles without error:

public void onCreate(SQLiteDatabase db)
{
    db.execSQL(DbMeta.T_DISGUISED.T_CREATE);
}

Despite this declaration (in javadoc popup):

void android.database.sqlite.SQLiteDatabase.execSQL(String sql) throws SQLException

So first, monkjack is right when he points out that onCreate method's signature cannot be changed by inheriting implementations.
And second, Zeki is correctly indicating the difference between checked and unchecked exceptions.

And now third, I want to add that the big confusion is caused by SQLException.

The SQLException used in the example above is Android type android.database.SQLException and inherits java.lang.RuntimeException - it is an unchecked exception! No throws declaration required!!!

That is not the classic java.sql.SQLException - which is a java.lang.Exception and requires try/catch/throws.

紫竹語嫣☆ 2024-10-17 06:48:18

您无法“通过 eclipse 在 android 中添加 throws”的原因是因为您不是定义接口或超类的人。如果您想向方法签名添加异常(就像您所说的通常那样),它也需要添加到接口中,并且您无法控制它们,因此无法更改它。

例如方法

protected void onCreate(Bundle savingInstanceState);

您在活动中重写它,如果您想引发异常,则需要将方法签名更改为(例如)

protected void onCreate(Bundle savingInstanceState) throws MyException;

但随后它还需要更改 onCreate 的定义位置,即 Activity 类中的位置 - 这是一个您无法更改的类(因为它由 android 库提供)。

因此,您唯一的选择是捕获异常并对其执行某些操作(或忽略它)。你可以做一个吐司来显示错误

catch (Exception e) {
  Toast toast = Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT);
  toast.show();
}

The reason you can't "add the throws in android via eclipse" is because you are not the person who defines the interfaces or super classes. If you want to add an exception to the method signature (like you say you do normally) it also needs to be added to the interface and you are not in control of them so you can't change it.

Eg the method

protected void onCreate(Bundle savedInstanceState);

which you override in activity, if you want to throw an exception the method signature would need to be changed to (for example)

protected void onCreate(Bundle savedInstanceState) throws MyException;

but then it would also need to change where onCreate is defined, which is in the Activity class - and that is a class you can't change (because its provided by the android library).

Therefore your only option is to catch the Exception and do something with it (or just ignore it). You could make a toast to display the errror

catch (Exception e) {
  Toast toast = Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT);
  toast.show();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文