Java 實例 - 異常處理方法

Java 實例 Java 實例

以下實例演示了使用 System 類的 System.err.println() 來展示異常的處理方法:

ExceptionDemo.java 檔

class ExceptionDemo { public static void main(String[] args) { try { throw new Exception("My Exception"); } catch (Exception e) { System.err.println("Caught Exception"); System.err.println("getMessage():" + e.getMessage()); System.err.println("getLocalizedMessage():" + e.getLocalizedMessage()); System.err.println("toString():" + e); System.err.println("printStackTrace():"); e.printStackTrace(); } } }

以上代碼運行輸出結果為:

Caught Exception
getMessage():My Exception
getLocalizedMessage():My Exception
toString():java.lang.Exception: My Exception
printStackTrace():
java.lang.Exception: My Exception
   at ExceptionDemo.main(ExceptionDemo.java:5)

Java 實例 Java 實例