Java如何處理異常方法?

2019-10-16 22:29:19

在Java程式設計中,如何處理異常方法?

本例展示了如何使用System類的System.err.println()方法處理異常方法。

package com.yiibai;

public class ExceptionMethods {
    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 com.yiibai.ExceptionMethods.main(ExceptionMethods.java:6)