2012-07-17 96 views
0

这个问题在面试时被问到了我。在下面的代码片段中,try块的第三行出现异常。问题是如何让第四行执行。第三行应该在catch块本身。他们给了我一个'使用投掷和投掷'的提示。试着抓住异常继续执行

public void testCase() throws NullPointerException{ 
     try{ 
      System.out.println("Start"); 
      String out = null; 
      out.toString(); 
      System.out.println("Stop"); 

     }catch(NullPointerException e){ 
      System.out.println("Exception"); 
     } 
    } 

任何人都可以帮忙。提前致谢。

+4

把第四行的'finally'块? – hmjd 2012-07-17 13:10:37

+0

你的意思是在第三行抛出异常'out.toString();'如何从赋值语句抛出异常。 – munyengm 2012-07-17 13:11:53

+0

你想要执行第三行吗? 'out.toString()'?以前没有声明过,所以理想情况下它应该返回吗?结果你什么都不做,为什么?我的猜测是你想要执行第四行? – 2012-07-17 13:13:28

回答

6

首先,第三个行的try块发生异常 - 在out.toString(),而不是第二行。

而且我假设你想要的第四行执行(即打印停止)

有不同的方式,使下一行(打印停止)来执行,如果你想简单地使车站印刷:

public static void testCase() throws NullPointerException{ 
     try{ 
      System.out.println("Start"); 
      String out = null; 
      out.toString(); 
      System.out.println("Stop"); 

     }catch(NullPointerException e){ 
      System.out.println("Stop"); 
      System.out.println("Exception"); 
     } 
    } 

或给出的暗示

第三行应该在catch块本身

public static void testCase() throws NullPointerException{ 
     try{ 
      System.out.println("Start"); 
      String out = null; 
      Exception e = null; 

      try 
      { 
       out.toString(); 
      } 
      catch(Exception ex) 
      { 
       e = ex; 
      } 
      System.out.println("Stop"); 

      if(e != null) 
       throw e; 

     }catch(Exception e){ 
      System.out.println("Exception"); 
     } 
    } 

还有其他的方法可以做到这一点,例如。最后阻止等等。但是,由于所提供的信息量有限,而且要实现它的工作目标,以上就足够了。

2

你可以这样做:

public void testCase() throws NullPointerException{ 
     try{ 
      System.out.println("Start"); 
      String out = null; 
      out.toString(); 
     }catch(NullPointerException e){ 
      System.out.println("Exception"); 
     } finally { 
      System.out.println("Stop"); 
     } 
    } 
0

棘手的片断,问题是:

  • 什么,当你崩溃的内部地址,这里 out输出的发生,被替换为String,但它是null
  • 是否可以打印null String,附带一段代码集中注意力。

你可以重写行:("" + out).toString();传递到第四之一。 '现在'这不是一个技术性的采访,除非你必须对第三个问题提出第二个问题。

测试是:候选人在没有看到问题的所有部分时,或者问题嵌套时做了什么,是否能够请求帮助来理解真正的问题。评论后

编辑

除非你对此有何评论行,你必须捕捉损坏代码:

try { 
    // Corrupted code to avoid 
    String out = null; 
    out.toString(); 
} catch (Exception e) { 
    // Careful (and professionnal) signal 
    System.out.println("out.toString() : code to repair."); 
} 
System.out.println("Stop"); // will appear to console 
+1

让我来引用你的问题,如果在try-catch块中有15行代码,并且第五行出现异常,并且由于某些个人原因,我想执行其他行“然后他们暗示”使用投掷和投掷“。任何建议。 – 2012-07-17 14:00:48