2016-01-13 74 views
0

我想知道是否有拋出異常的簡單方法,但只有只有與我選擇的確切字符串。我發現了一個辦法擺脫的堆棧跟蹤,但現在我想刪除每個異常的開頭:拋出異常,沒有「Exception in thread ...」

「異常線程‘main’的RuntimeException ......」

我正在尋找一個簡單,優雅的方式來做到這一點(不是很簡單,但也不太複雜)。

謝謝!

+0

這是否有特別的原因? – Kayaman

+0

嗯......對我來說似乎有點多餘,因爲你要求的只是'try {...} catch(Exception e){System.err.print(「what ever」);}' –

+0

沒有特別的原因,我只是想知道這樣的事情是否可能以及如何。 – edle

回答

3

做,這是設置你自己的自定義正確的方法,uncaught exception handler:

public static void main(String... argv) 
{ 
    Thread.setDefaultUncaughtExceptionHandler((t, e) -> System.err.println(e.getMessage())); 
    throw new IllegalArgumentException("Goodbye, World!"); 
} 
+0

不會拋出新的IllegalArgumentException(「再見,世界!」);'打印'線程中的異常......'哪幾乎是正確的方式,雖然你100%正確的。 –

+0

@DimaMaligin試試看吧 – erickson

+1

你是對的!(+1),從來沒有注意到它之前... –

0

這是你如何做到這一點:

try{ 
    //your code 
}catch(Exception e){ 
    System.out.println("Whatever you want to print" + e.getMessage()); 
    System.exit(0); 
} 
+0

這是一個簡單的打印輸出...我想通過拋出異常來停止程序。 – edle

+0

就像在catch子句中添加System.exit一樣? –

0

當你構建一個異常對象,一個構造函數將採取消息的String對象。

0

你不能,除非你得到openJDK,改變源代碼並重新編譯。

但是,根據日誌記錄設置,大多數開發人員通常會使用某些日誌記錄庫(如log4j)並使用不同的詳細級別。

因此,您可以使用較低級別(例如TRACE或DEBUG)打印完整的堆棧跟蹤,並在ERROR或WARN(甚至INFO)級別中輸出更易於理解的消息。

1

只要做到:

try { 
    ... 
} catch (Exception e) { 
    System.err.print("what ever"); 
    System.exit(1); // close the program 
} 
+0

爲什麼我忘了System.err.print()? :(謝謝! – edle

+0

@edle歡迎你接受答案,如果它回答你的問題... –

0

我不知道我完全理解你的問題,但如果你只需要添加「拋出異常」的方法,頭和拋出異常的地方應該失敗的方法,這應該工作。

例子:

public void HelloWorld throws Exception{ 
    if(//condition that causes failure) 
     throw new Exception("Custom Error Message"); 
    else{ 
     //other stuff... 
    } 
} 
0

您可以通過創建自定義Exception,你可以創建自己做到這一點。

  • 這些異常可以是Checked異常,由Java編譯器執行(要求的try/catch或拋出來實現)
  • 或者異常可以Unchecked例外,它在運行時拋出,未執行由Java編譯器。

根據你所寫的內容,似乎你想要一個Unchecked異常,但不是強制執行,而是在運行時引發錯誤。

這樣做的一種方式是通過以下事項:

public class CustomException extends RuntimeException { 
     CustomException() { 
       super("Runtime exception: problem is..."); // Throws this error message if no message was specified. 
     } 

     CustomException(String errorMessage) { 
      super(errorMessage); // Write your own error message using throw new CustomException("There was a problem. This is a custom error message"); 
     } 
} 

然後在你的代碼,你可以做到以下幾點:

public class Example { 
    String name = "x"; 
    if(name.equals("x")) 
      throw new CustomException(); // refers to CustomException() 
} 

或者

public class Example2 { 
     String name = "y"; 
     if(name.equals("y")) 
      throw new CustomException("Error. Your name should not be this letter/word."); // Refers to CustomException(String errorMessage); 
} 

你也可以爲Throwable做這個。

+0

這是非常基本的異常處理...我試圖避免堆棧跟蹤和每個異常文本的開始。 – edle