2012-12-11 65 views
2

我正在爲星期五的CS考試而學習,並且在這裏的路上碰到一個碰撞。這個問題讓我去處理這個異常,然後用兩種不同的方法來傳播這個異常,但我覺得他們是一樣的。誰能幫忙?練習題如下所示。繁殖與處理有什麼區別?

您將得到下面的類:

public class ReadData { 
    public void getInput() { 
    getString(); 
    getInt(); 
    } 

    public void getString() throws StringInputException { 
    throw new StringInputException(); 
    } 

    public void getInt() throws IntInputException { 
    throw new IntInputException(); 
    } 
} 

class StringInputException extends Exception {} 

class IntInputException extends Exception {} 

上面的代碼將導致getInput編譯錯誤()方法。 使用兩種不同的技術重寫getInput()方法:

Method 1 - Handle the exception 

Method 2 - Propagate the exception 

使得代碼編譯。

回答

5

他們不是一回事。傳播基本上意味着重新拋出異常,也就是允許代碼中的某個地方處理它;一般情況下,如果在當前層面上對異常做不了任何事情,就可以做到這一點。處理異常意味着捕獲異常並實際做一些事情 - 通知用戶,重試,日誌記錄 - 但不允許異常繼續。

2

「處理異常」意味着要抓住它並做任何必要的事情才能正常繼續。

「傳播異常」意味着不抓住它並讓你的調用者處理它。

0

dictionary.com是你的朋友在這一個。有時候我們不得不面對那個討厭的英語。

手柄裝置做一些不同之處, 中止程序, 打印錯誤, 勾搭數據...

傳播這意味着將其轉發到別的地方重新即扔。

4
class Example { 
    // a method that throws an exception 
    private void doSomething() throws Exception { 
     throw new Exception(); 
    } 

    public void testHandling() { 
     try { 
      doSomething(); 
     } catch (Exception e) { 
      // you caught the exception and you're handling it: 
      System.out.println("A problem occurred."); // <- handling 
      // if you wouldn't want to handle it, you would throw it again 
     } 
    } 

    public void testPropagation1() throws Exception /* <- propagation */ { 
     doSomething(); 
     // you're not catching the exception, you're ignoring it and giving it 
     // further down the chain to someone else who can handle it 
    } 

    public void testPropagation2() throws Exception /* <- propagation */ { 
     try { 
      doSomething(); 
     } catch (Exception e) { 
      throw e; // <- propagation 
      // you are catching the exception, but you're not handling it, 
      // you're giving it further down the chain to someone else who can 
      // handle it 
     } 
    } 
}