【问题标题】:Questions regarding internal code of a try catch block previous to an exception关于异常之前的 try catch 块的内部代码的问题
【发布时间】:2017-03-14 16:19:50
【问题描述】:

我有一个这样的 try 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 是一个全局变量。

当设备在内部 try-catch 块中没有给出异常时,全局变量 deviceCompatibleWithMaps 是否应该在所有情况下存储真实值?或者如果 Throwable is Error 或 Exception 在上面的 trycatch 块中被抛出,它的值可能不会被保存?

我在一个应用程序中遇到了一个罕见的错误,有时全局的值没有被存储,我怀疑在 try catch 块上的异常下执行的分配将不会被安全地存储。

【问题讨论】:

  • 为什么不把this.globalBool = true;放在外面试试呢?还是在finally 块中?
  • 这只是一个示例代码,实际代码要复杂得多
  • 您应该提供您的具体问题。此代码globalBool 将始终为真。
  • globalBool 不是全局变量。
  • “这只是一个示例代码” - 是的,但是一个什么示例?不是你问的问题。所以没用。

标签: java android try-catch


【解决方案1】:

我看不出this.globalBool = true; 怎么会失败,所以它总是设置为true,除非functionWhichCrash() 中的代码更改了它(另一个线程)。

编辑:自从我写下这个答案以来,这个问题已经完全改变了。新答案:

如果GeoPoint dummy = new GeoPoint(0, 0); 失败,deviceCompatibleWithMaps 将永远不会设置为 true。

【讨论】:

  • 是的,我知道,问题是这样的功能在 nexus 5X 中永远不会失败,问题不存在
  • 当你说全局的值没有被存储,你的意思是全局的值没有被设置为true?实际上,如果该行永远不会失败,则只有 functionThatCanCrash(); 中的另一个线程或代码可以将其设置为 false。
【解决方案2】:

如果GeoPoint 的初始化引发异常,则布尔值永远不会设置为真。如果您使用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。

异常层次结构中的通知Throwable 位于顶部。每个ErrorExceptionRuntimeException 等都从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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-10
    • 1970-01-01
    • 1970-01-01
    • 2019-11-11
    • 1970-01-01
    • 1970-01-01
    • 2012-07-03
    相关资源
    最近更新 更多