尝试使用这样的catch块:
try {
try {
GeoPoint dummy = new GeoPoint(0, 0);
deviceCompatibleWithMaps=true;
} catch (Throwable t) {
t.printStackTrace();
deviceCompatibleWithMaps=false;
}
functionThatCanCrash();
} catch (Throwable t) {
t.printStackTrace();
}
* GeoPoint dummy = new GeoPoint(0,0);在我的nexus 5x测试设备中永远不会失败 * deviceCompatibleWithMaps是一个全局变量
当设备没有在内部trycatch块中给出异常时,全局变量deviceCompatibleWithMaps应该在所有情况下存储真值吗?或者如果Throwable是错误或者异常被抛出在上面的trycatch块中,它的值是否会被保存?
我在一个应用程序中有一个罕见的错误,有时全局的值没有被存储,我怀疑在try catch块上的异常下执行的asignations将无法安全存储
谢谢。
答案 0 :(得分:1)
我无法看到this.globalBool = true;
如何失败,所以它始终设置为true,除非functionWhichCrash()
中的代码更改它(其他另一个线程)。
如果GeoPoint dummy = new GeoPoint(0, 0);
失败,deviceCompatibleWithMaps
永远不会设置为true。
答案 1 :(得分:1)
如果GeoPoint
的初始化抛出异常,则布尔值永远不会设置为true。如果您使用Boolean
作为对象,它将是null
,但如果您使用原始boolean
,则默认为false。你应该尝试改为
try {
GeoPoint dummy = new GeoPoint(0, 0);
deviceCompatibleWithMaps = true;
functionThatCanCrash();
} catch (CustomException t) {
// logic for one exception
} catch (CalendarNotCompatibleException t) {
// logic for other exception
deviceCompatibleWithMaps = false;
}
}
在异常层次结构中注意Throwable
位于顶部。每个Error
,Exception
,RuntimeException
等都来自Throwable
。您将捕获应用程序中发生的每个可能的错误。
Error类中的JavaDoc特别指出不应该捕获这些异常。
* An <code>Error</code> is a subclass of <code>Throwable</code>
* that indicates serious problems that a reasonable application
* should not try to catch. Most such errors are abnormal conditions.
* The <code>ThreadDeath</code> error, though a "normal" condition,
* is also a subclass of <code>Error</code> because most applications
* should not try to catch it.
* A method is not required to declare in its <code>throws</code>
* clause any subclasses of <code>Error</code> that might be thrown
* during the execution of the method but not caught, since these
* errors are abnormal conditions that should never occur.
*
* @author Frank Yellin
* @version %I%, %G%
* @see java.lang.ThreadDeath
* @since JDK1.0