zoukankan      html  css  js  c++  java
  • Java异常中getMessage()与toString的区别

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

    示例代码1

    public class TestInfo {
        private static String str =null;
        public static void main(String[] args) {
            System.out.println("test exception");
            try {
                if(str.equals("name")){
                    System.out.println("test exception");
                }
            } catch (Exception e) {
                System.out.println(e.toString());
                System.out.println(e.getMessage());
            }
        }
    }

    输出结果:
    java.lang.NullPointerException
    null
    示例代码2:

    public class TestInfo {
        private static int m = 0;
        public static void main(String[] args) {
            System.out.println("test exception");
            try {
                m = 899/0;
            } catch (Exception e) {
                System.out.println(e.toString());
                System.out.println(e.getMessage());
            }
        }
    }

    输出结果:

    java.lang.ArithmeticException: / by zero
    / by zero
    总结:

    e.toString(): 获得异常种类和错误信息

    e.getMessage():获得错误信息

    e.printStackTrace():在控制台打印出异常种类,错误信息和出错位置等
    ---------------------
    原文链接:https://blog.csdn.net/opera95/article/details/74885827

  • 相关阅读:
    ZOJ 1450
    HDU 3932
    POJ 3348
    POJ 1873
    POJ 1228
    POJ 2007
    POJ 1113
    POJ 1696
    POJ 1329
    HDU 3432
  • 原文地址:https://www.cnblogs.com/GG-Bond/p/11364066.html
Copyright © 2011-2022 走看看