Java异常———获取异常的具体信息、获取异常类型、将异常栈转为String字符串

背景:

接口采用定时任务方式向MQ推送数据,每秒推送一条数据记录,因为量太大导致出了异常后无法追溯,于是需要将异常栈信息转为字符串保存到数据库中,这样就可以直接通过数据库知道记录推送失败的原因。

e:异常类型+具体异常信息;

e.getMessage():具体异常信息;

代码:

package sort;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;


public class ExceptionExample {
	@SuppressWarnings("null")
	public static void main(String[] args) {
		String text = null;
		try {
			InputStream is =new ByteArrayInputStream(text.getBytes("UTF-8"));
		} catch (Exception e) {
			System.out.println("引起异常的原因------>"+getExceptionType(e));
			System.out.println("异常信息------>"+getExceptionMessage(e));
			System.out.println("异常跟踪栈------>"+getExceptionSrintStackTrace(e));
		}
	}
	public static Throwable getExceptionType(Exception e) {
		return e;
	}
	public static String getExceptionMessage(Exception e) {
		return e.getMessage();
	}
	public static String getExceptionSrintStackTrace(Exception e) {
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);
		e.printStackTrace(pw);
		return sw.toString();
	}
	public static int number() {
		return 10/0;
	}
}

控制台:

引起异常的原因------>java.lang.NullPointerException
异常信息------>null
异常跟踪栈------>java.lang.NullPointerException
	at sort.ExceptionExample.main(ExceptionExample.java:14)

代码:

package sort;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;

import javax.sound.midi.MidiDevice.Info;

public class ExceptionExample {
	public static void main(String[] args) {
		try {
			int b = number();
		} catch (Exception e) {
			System.out.println("异常类型------>"+getExceptionType(e));
			System.out.println("异常信息------>"+getExceptionMessage(e));
			System.out.println("异常跟踪栈------>"+getExceptionSrintStackTrace(e));
		}
	}
	public static Throwable getExceptionType(Exception e) {
		return e;
	}
	public static String getExceptionMessage(Exception e) {
		return e.getMessage();
	}
	public static String getExceptionSrintStackTrace(Exception e) {
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);
		e.printStackTrace(pw);
		return sw.toString();
	}
	public static int number() {
		return 10/0;
	}
}

控制台:

异常类型------>java.lang.ArithmeticException: / by zero
异常信息------>/ by zero
异常跟踪栈------>java.lang.ArithmeticException: / by zero
	at sort.ExceptionExample.number(ExceptionExample.java:34)
	at sort.ExceptionExample.main(ExceptionExample.java:14)

 

  • 5
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值