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)

 

你可能感兴趣的:(Java)