了解 Try Catch 块行为

Understanding the Try Catch block behavior

我 运行 陷入了 try catch 的一个 st运行ge 问题,这让我怀疑我自己对异常处理基础知识的认识。根据基本语法

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){}

}
}

我还没有初始化,

public class Ideone{
public static void main (String[] args) throws java.lang.Exception
{

    int i = 0;

    try{ 


            if(i<2)
            System.out.println("Inner Block");

      System.out.println("Outer Block");        

    }catch(Exception e){}

}
}

你确定你的问题吗?我相信您的 catch 中有一些尚未初始化的清理代码 - 因此是异常。如果您 post 您的实际代码会有所帮助。 以下按预期工作:

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){}
}

}

无法重现。 我试过了

public static void main (String[] args) throws java.lang.Exception
    {
        Collection c = null ;
        try{ 
            for(Object i:c)
                System.out.println("Inner Block");
            System.out.println("Outer Block");        
        }catch(Exception e){}
    }

效果很好。

以下代码片段打印 "An exception!"

List<String> strings = null;
try {
    for (String s : strings) {
        System.out.println(s);
    }
} catch (Exception e) {
    System.out.println("An exception!");
}

正如其他人指出的,您自己也说过,Runtime exceptions are caugth by Exception catches

您是否尝试过从头开始重新编译所有代码?在我的团队(250.000 行代码库)中使用 eclipse,我们有时会遇到错误的编译问题,这些问题可能会产生无法解释的问题,例如这样。我们通常通过完全重新编译来解决它们。

Understanding the Try Catch block behavior?

使用 try-catch 块的主要原因是为了处理您的代码出现的问题或正常情况下您意想不到的事情,并且某些事情会以某种方式抛出异常并在 [=12] 中处理它=] 块,finally 块几乎用于 close 任何打开的流,即使 trycatch 返回任何值(系统终止除外)。

在你的代码中,似乎有一些你从数据库中得到的东西是 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,当您尝试使用空对象时会抛出它。