怎么获取e.printStackTrace()中的第一行信息
时间: 2023-01-30 20:20:35 浏览: 83
可以使用 Throwable 类的 getStackTrace() 方法来获取 e.printStackTrace() 中的堆栈信息,然后通过堆栈信息数组的第一个元素来获取第一行信息。例如:
```
try {
// some code that may throw an exception
} catch (Exception e) {
StackTraceElement firstLine = e.getStackTrace()[0];
String className = firstLine.getClassName();
String fileName = firstLine.getFileName();
int lineNumber = firstLine.getLineNumber();
// do something with the information
}
```
如果想要获取完整的堆栈信息,可以使用 e.printStackTrace() 方法将堆栈信息打印到标准错误流中,或者使用 StringWriter 和 PrintWriter 将堆栈信息写入字符串中。例如:
```
try {
// some code that may throw an exception
} catch (Exception e) {
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
e.printStackTrace(printWriter);
String stackTrace = stringWriter.toString();
// do something with the stack trace
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)