软件编程
位置:首页>> 软件编程>> java编程>> 浅谈Java异常的Exception e中的egetMessage()和toString()方法的区别

浅谈Java异常的Exception e中的egetMessage()和toString()方法的区别

作者:jingxian  发布时间:2022-05-27 00:37:31 

标签:egetMessage,toString,java

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());
   }
 }
}

输出结果:


; font-family:" microsoft="" background-color:="" /> 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()只是获取了异常的详细消息字符串。

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com