避免在Android的try / catch [英] Avoid try/catch on Android
问题描述
我在Android的新环境,我已经开始写一些code到数据库上执行一些查询。当我有处理异常,我不知道合适的方法是做什么它 - 出来的Android的我用的方法抛出
声明,但似乎抛出
不在Android的允许?刚的try-catch
?
我这样说是因为Eclipse不建议我加入罚球
我出的Android环境的时候喜欢声明,我猜测它是关系到延伸活动
。
那么,什么是处理在android系统异常的适当方法?周围有每一句的try-catch
让我的code别看这不是真的是我想要做的。
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);
}
}
另一个选择是让 MyException
延长的RuntimeException
。那么编译器不会强迫你抓住它或把它的方法。 RuntimeExceptions被称为的 unchecked异常的意思是你没有检查他们发生。这方面的例子是空指针
和 ArrayOutOfBounds
。
The other option is to make MyException
extend RuntimeException
. Then the compiler won't force you to catch it or put it in the method. RuntimeExceptions are known as unchecked exceptions meaning you don't have to check for them occurring. Examples of these are NullPointer
and ArrayOutOfBounds
.
这篇关于避免在Android的try / catch的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!