在Java中,可以通过以下几种方式获取e.printStackTrace()
打印的信息:
- 使用
e.printStackTrace()
打印异常信息到控制台:
try { // some code that may throw an exception } catch (Exception e) { e.printStackTrace(); // 打印异常信息到控制台 }
- 使用
StringWriter
将异常信息输出到字符串:
try { // some code that may throw an exception } catch (Exception e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); String exceptionAsString = sw.toString(); // 将异常信息输出为字符串 }
- 使用
ByteArrayOutputStream
将异常信息输出到字节数组:
try { // some code that may throw an exception } catch (Exception e) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); e.printStackTrace(ps); byte[] exceptionAsBytes = baos.toByteArray(); // 将异常信息输出为字节数组 }
这些方法可以根据具体的需求选择适合的方式来获取异常信息,并根据需要进行处理或记录。