了解Try Catch块行为

时间:2015-11-09 06:40:06

标签: java try-catch

我在try catch遇到了一个奇怪的问题让我怀疑自己对异常处理基础的实现。根据基本语法

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

}
}

5 个答案:

答案 0 :(得分:1)

以下代码段打印“异常!”

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

您是否尝试过从头开始重新编译所有代码?在使用eclipse的我的团队(250.000行代码库)中,我们有时会遇到可能会出现无法解释的问题的糟糕编译问题。我们通常通过完整的重新编译来解决它们。

答案 1 :(得分:0)

您确定自己的问题吗?我相信你的捕获中有一些清理代码尚未初始化 - 因此是个例外。如果您发布实际代码会有所帮助。 以下按预期工作:

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

}

答案 2 :(得分:0)

  

了解Try Catch阻止行为?

使用try-catch阻止的主要原因是处理某些代码会出错或者你正常情况下意外的东西,某些东西会以某种方式抛出异常并在catch处理它阻止,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) {} } } 是否MainCtrl,然后像这样使用它:

$routeProvider

NullPointerException扩展了RuntimeException,并在尝试使用null对象时抛出它。

答案 3 :(得分:-1)

我还没有初始化,

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

}
}

答案 4 :(得分:-2)

无法重现。 我试过这个

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

效果很好。