e.getMessage()和e.toString() 和e.printStackTrace()对比

一. java中e.getMessage()和e.toString() 以及e.printStackTrace()比较

e.getMessage()
只获取异常信息的字符串(不含异常类型)

e.toString()
获取异常类型和异常详细信息

e.printStackTrace()
打印出异常类型和异常详细信息,并且显示异常在后台代码中出现的位置。

案例:

public class ExceptionTest {

	public static void main(String[] args) {
		try {
			System.out.println(1/0);
		} catch (Exception e) {
			System.out.println("e.getMessage():"+e.getMessage());
			System.out.println("————————————————————");
			System.out.println("e.toString():"+e.toString());
			System.out.println("————————————————————");
			e.printStackTrace();
		}
	}
}

空值台打印结果:

除以零
————————————————————
java.lang.ArithmeticException: 除以零
————————————————————
java.lang.ArithmeticException: 除以零
at com.eric.test.ExceptionTest.main(ExceptionTest.java:7)

二. PrintStackTraceUtil

有些时候,我们在后台catch捕获异常后,希望能将异常具体的报错信息和位置存入数据库中,便于后期跟踪并解决问题,此时我们可以将e.printStackTrace()输出的信息转换成字符串,再将字符串保存到数据库中,以下是将e.printStackTrace()输出信息转换成String字符串的工具类

public class PrintStackTraceUtil {

	/**
     * 获取e.printStackTrace() 的具体信息,赋值给String 变量,并返回
     * 
     * @param e	Exception
     *            
     * @return e.printStackTrace() 中 的信息
     */
    public static String getStackTraceInfo(Exception e) {

        StringWriter sw = null;
        PrintWriter pw = null;

        try {
            sw = new StringWriter();
            pw = new PrintWriter(sw);
            e.printStackTrace(pw);//将出错的栈信息输出到printWriter中
            pw.flush();
            sw.flush();

            return sw.toString();
        } catch (Exception ex) {

            return "发生错误";
        } finally {
            if (sw != null) {
                try {
                    sw.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (pw != null) {
                pw.close();
            }
        }

    }
}
  • 7
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值