尝试捕捉遇到了一个奇怪的问题,这让我对自己的异常处理基本原理的实现产生了怀疑。根据基本语法
try{
code to be checked
}
catch(Exception e){}
finally{}然而,下面的代码给了我一个空指针异常,我认为它应该被捕获。
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
try{
for(Model m: Null Collection coming from DB)
System.out.println("Inner Block");
System.out.println("Outer Block");
}catch(Exception e){}
}
}发布于 2015-11-09 07:05:20
下面的片段打印“一个异常!”
List<String> strings = null;
try {
for (String s : strings) {
System.out.println(s);
}
} catch (Exception e) {
System.out.println("An exception!");
}正如其他人所指出的,你自己也说过,运行时异常是由异常捕获引起的。
您试过从头开始重新编译所有代码吗?在我的团队(250.000行代码基)中,使用eclipse时,我们有时会遇到错误的编译,这些编译可能会出现这样无法解释的问题。我们通常通过一个完整的重新编译来解决这些问题。
发布于 2015-11-09 06:51:44
你确定你的问题吗?我相信在您的捕获中有一些清理代码尚未初始化,因此出现了例外。如果你贴出你的实际代码。预期的工作如下:
import java.util.List;
public class Main {
public static void main(String[] args) {
List i=null;
try{
for(Object o: i) {
System.out.println("Inner Block");
}
System.out.println("Outer Block");
}catch(Exception e){}
}}
发布于 2015-11-09 07:21:48
了解尝试捕获块行为吗?
使用try-catch块的主要原因是处理某些代码会出错或在正常情况下意外发生的事情,某些东西会以某种方式抛出异常并在catch块中处理它,而finally块几乎用于close任何打开的流,即使try或catch返回任何值(系统终止除外),它也每次在代码中运行。
在您的代码中,似乎有些东西是从数据库中得到的,它们是null或尚未初始化,或者它已经从空值的数据库中返回,现在如果还没有初始化它,就不能使用null对象!您必须确保它是否是null,然后像这样使用它:
class Ideone {
public static void main(String[] args) throws java.lang.Exception {
try {
if(Null Collection coming from DB != null){
for(Model m: Null Collection coming from DB)
System.out.println("Inner Block");
}
System.out.println("Outer Block");
} catch (Exception e) {}
}
}NullPointerException是扩展RuntimeException,当您尝试使用null对象时会抛出它。
https://stackoverflow.com/questions/33603695
复制相似问题