Exception 的 toString() 方法和 getMessage() 方法的区别

Exception 的 toString() 方法和 getMessage() 方法的区别:

    在开发的过程中打印错误日志时尽量使用e.toString() 方法,

    因为当错误为空指针时 e.getMessage() 提示的错误信息为 null , e.toString() 方法比 e.getMessage() 方法要详细,实例如下:

public class TestException {

    public static String str = null;
    
    public static void main(String[] args) {
        try {
            if (str.isEmpty()) {
                System.out.println("------");
            }
        } catch (Exception e) {
            System.out.println("e.getMessage():      " + e.getMessage());
            System.out.println("e.toString:      " + e.toString());
        }
    }
}

如上代码运行显示的结果:

e.getMessage():      null
e.toString:      java.lang.NullPointerException