2011-03-29 94 views
0

如果我写这样的代码:关于产品的try catch语句

Document d = searcher.doc(docId); 
d.get("latitude") 

我得到

unreported exception ... must be caught or declared to be thrown 

如果我写这篇文章,

try { 
    Document d = searcher.doc(docId); 
} 
d.get("latitude") 

我显然得到:

cannot find symbol 
symbol : variable d 

如果我写这篇文章

Document d; 
try { 
d = searcher.doc(docId); 
} 
d.get("latitude"); 

我得到这个:

variable d might not have been initialized 

因为我不想try/catch语句扩展到所有的文件我怎么能解决这个问题呢?

感谢

回答

4
Document d = null; 

,而不是仅仅

Document d; 

虽然那么你不必担心NullPointerException异常后在路上,当你使用d

2

你这样做有消息说什么: 只需在开头初始化变量“d”为空:

Document d = null; 
try { 
    d = searcher.doc(docId); 
} 
d.get("latitude"); 

无论如何,要小心!如果发生异常,你的“d”变量将为空,你将得到一个对象引用而不是异常! 在try块中包含d.get("latitude");或在调用该行之前检查null。

3

尝试:

Document d = null; 
try { 
    d = searcher.doc(docId); 
    d.get("latitude"); 
} 
0

应该是:

Document d = null; 
try { 
    d = searcher.doc(docId); 
} catch (Exception e) { 
    //... 
} 
d.get("latitude"); 
+0

如果catch语句本身不会抛出异常,则d可能为空 – Adi 2011-03-29 22:45:00

+0

我知道,那么我们将会有NPE,它显示不正确的应用程序状态 – smas 2011-03-29 22:58:18

0

你只需把它初始化为空,但是你不应该在我看来。

如果该方法抛出一个异常,那么d == null,所以你需要处理这种情况,if (d != null)或只是范围d在try块内。

我会做后者。

1

您应该初始化变量并捕获异常(您可以根据需要更改异常名称并获取消息级别)。

Document d = null; 
try { 
    d = searcher.doc(docId); 
    d.get("latitude"); 
} catch (Exception ex){ 
    ex.getMessage(); 
} 
0

如果你钓到的鱼会导致跳过(通过退货或throw语句)的方法的其余部分,或者如果你在catch初始化d,你不应该得到这个错误。 。

Document d; 
try { 
    d = searcher.doc(docId); 
} catch (SomeException e) { 
    return null; 
    //throw new RuntimeException(e); 
    //d = some default value 
} 
d.get("latitude"); 

刚刚初始化d = null时,只会在发生异常时导致空指针(模糊实际原因)。