java将抛出的exception打印成字符串

public static String printException(Throwable throw) {
	if (throw == null) {
		return "";
	}
	
	ByteArrayOutputStream out = new ByteArrayOutputStream();
	try {
		throw.printStackTrace(new PrintStream(out));
		out.flush();
	} catch (Exception e){
		e.printStackTrace();
	} finally {
		if (out != null)
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
	}
	return out.toString();
}

因为Exception是Throwable的子类,所以直接传Throwable作为参数

猜你喜欢

转载自z724130632.iteye.com/blog/2315515