2012-07-17 93 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