2016-02-27 62 views
1

我看到很多人寫的一樣:如何在java中拋出SystemException?

try { 
     //something 
} 
catch (IOException e){ 
    throw new SystemException("IO Error", e); 
} 

"Cannot instantiate the type SystemException"錯誤,似乎是SystemException的一個抽象類,我該怎麼能夠把它扔?

回答

0

是的,它是一個抽象類,這意味着構建一個SystemException類型的對象是沒有意義的。建議使用更有意義的異常類型。您的代碼中提到了IOException。這意味着與I/O操作相關的異常,捕獲器可以相應地執行操作(可能是特殊的日誌級別,某些I/O清理等)。

你的具體情況,我想你應該將其更改爲:

try { 
    //something 
} 
catch (IOException e) { 
    // log exception info and other context information here 
    // e.g. e.printStackTrace(); 

    // just rethrowing the exception (call stack is still there) 
    throw e; 
} 

附:很不重要,但來自.NET世界,我發現subtle difference之間throw ex;C#Java之間。

+0

所以我可能應該寫在catch上的東西就像下面的東西?謝謝 e.printStackTrace(); 扔e; – Tokoyomi

+0

@Tokoyomi - 是的,這是可能的。在較大的應用程序中,使用日誌記錄庫來允許更多日誌記錄選項。例如。 [log4j的](http://logging.apache.org/log4j/2.x/) – Alexei