Java获取e.printStackTrace()打印的信息方式
作者:小诸葛的博客 时间:2022-05-18 05:19:26
获取e.printStackTrace()打印的信息
某些情况下,我们需要获取应用打印的异常信息,这时就可以借助StringWriter和PrintWriter两个类来获取异常信息
具体用法如下:
try{
throw new NullPointerException();
}catch (Exception e){
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw,true));
String infomsg = sw.toString();
System.out.println(infomsg);
}
e和e.printStackTrace()方法
e初始化,也就是实例化Exception类型的对象,e是此对象引用名称。然后e(引用)会自动调用Exception类中指定的方法,也就出现了e.printStackTrace()。
当然,我们也可以用System语句输出,那么这两个语句有什么区别呢?
1、两个输出语句都能输出
System语句可以提示你异常发生的位置;但e.printStackTrace()可以显示更深的调用关系。
例如:程序中有继承的关系
Rose extends Flower ; Flower extends Plant;假如我们在创建 Rose
的时候发生异常,那么System语句就会输出异常 at Rose ,然后向外层输出
但e.printStackTrace()输出除了标准异常外,打印 at Plant at Flower at Rose
…….再向外层调查。 在向外层调查的情况下,都一样
2、System.out.println();
当发生异常时显示你自己设定的字符串信息;e.printStackTrace();是打印异常的堆栈信息,指明错误原因。
note:其实当发生异常时,通常要处理异常,这是编程的好习惯,所以e.printStackTrace()可以方便你调试程序!
来源:https://blog.csdn.net/LONG_Yi_1994/article/details/109724945
标签:Java,e.printStackTrace,打印
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Android RecyclerBarChart绘制使用教程
2023-06-19 12:18:36
![](https://img.aspxhome.com/file/2023/1/83521_0s.png)
java连接sql server 2008数据库代码
2023-05-27 10:40:01
使用logback屏蔽一些包的日志
2023-08-08 20:46:20
详解Struts2动态方法调用
2022-10-18 11:19:25
通过源码角度看看AccessibilityService
2023-07-25 09:31:43
![](https://img.aspxhome.com/file/2023/2/84752_0s.jpg)
java字符串相似度算法
2023-11-26 12:33:25
Java枚举学习之定义和基本特性详解
2022-07-23 20:29:44
![](https://img.aspxhome.com/file/2023/5/64525_0s.png)
详解java中的PropertyChangeSupport与PropertyChangeListener
2023-10-20 06:19:27
浅析Java中Apache BeanUtils和Spring BeanUtils的用法
2021-07-10 21:29:15
![](https://img.aspxhome.com/file/2023/4/63324_0s.jpg)
Spring MVC请求参数接收的全面总结教程
2023-11-28 19:44:47
![](https://img.aspxhome.com/file/2023/1/60701_0s.png)
关于Mybatis-Plus Wrapper是否应该出现在Servcie类中
2023-11-28 22:04:56
springboot整合shiro与自定义过滤器的全过程
2023-11-24 21:02:40
关于@GetMapping和@GetMapping(value=““)的区别
2023-11-27 11:07:37
![](https://img.aspxhome.com/file/2023/2/59992_0s.png)
Java logback日志的简单使用
2023-07-15 01:32:33
ElasticSearch添加索引代码实例解析
2023-11-21 03:41:04
![](https://img.aspxhome.com/file/2023/3/59543_0s.png)
Kafka Producer中的消息缓存模型图解详解
2022-05-03 06:00:13
![](https://img.aspxhome.com/file/2023/2/61012_0s.jpg)
Android 如何实现动态申请权限
2023-07-30 00:51:31
Java之操作Redis案例讲解
2023-06-18 03:48:41
![](https://img.aspxhome.com/file/2023/8/61288_0s.png)
Spring Boot Redis 集成配置详解
2022-12-05 20:57:59
Java服务器主机信息监控工具类的示例代码
2023-07-26 04:34:49
![](https://img.aspxhome.com/file/2023/0/57730_0s.png)