Java 实例 - 异常处理方法


以下实例演示了使用 System 类的 System.err.println() 来展示异常的处理方法:

  1. /*
  2. author by shouce.ren
  3. ExceptionDemo.java
  4. */
  5.  
  6.  
  7. class ExceptionDemo
  8. {
  9. public static void main(String[] args) {
  10. try {
  11. throw new Exception("My Exception");
  12. } catch (Exception e) {
  13. System.err.println("Caught Exception");
  14. System.err.println("getMessage():" + e.getMessage());
  15. System.err.println("getLocalizedMessage():"
  16. + e.getLocalizedMessage());
  17. System.err.println("toString():" + e);
  18. System.err.println("printStackTrace():");
  19. e.printStackTrace();
  20. }
  21. }
  22. }

以上代码运行输出结果为:

  1. Caught Exception
  2. getMessage():My Exception
  3. getLocalizedMessage():My Exception
  4. toString():java.lang.Exception: My Exception
  5. printStackTrace():
  6. java.lang.Exception: My Exception
  7. at ExceptionDemo.main(ExceptionDemo.java:5)