避免在Android上使用try / catch [英] Avoid try/catch on Android

查看:116
本文介绍了避免在Android上使用try / catch的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Android环境中是新的,我已经开始编写一些代码来对数据库执行一些查询。当我必须处理异常时,我不知道什么是适当的方式来做 - 在Android之前,我曾经在方法上使用 throws 声明,但似乎<$在android中不允许c $ c> throws 只是 try-catch
我说这是因为eclipse不建议我添加 throws 声明,就像我在Android环境之外,我想它与扩展活动
那么在android中处理异常的适当方式是什么?使用 try-catch 使每个句子周围,使我的代码看起来很可怕,这不是我想要做的。

解决方案

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

  public void someMethod()throws IOException {
try {
// Do数据库操作
} catch(MyException e){
throw new IOException异常(e.toString());
}
}

//或者,如果没有异常,使用未经检查的异常:

public void otherMethod(){
尝试{
// DB操作
} catch(MyException e){
throw new RuntimeException(e);
}
}

另一个选项是使 MyException extends RuntimeException 。那么编译器就不会强迫你抓住它或者添加到方法签名中。 RuntimeExceptions被称为未检查异常,这意味着您不必通过try / catch方式检查它们。这些例子是 NullPointer ArrayOutOfBounds


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.

解决方案

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.

这篇关于避免在Android上使用try / catch的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆