打印异常信息 方法汇总
来源:互联网 发布:维纶触摸屏数据存储 编辑:程序博客网 时间:2024/04/29 18:13
平时写java代码时,想看抛出的异常信息,来找出具体的异常点,我们常常会用Exception.toString ()或者 Exception.getMessage()来取得异常信息,再把它print到控制台,,但是这些信息只能告诉我们异常本身的信息,对我们找出异常点帮助并不太理想,所以我们会使用Exception.printStackTrace()方法,这样就可以在控制台输出非常详细的异常信息,甚至可以通过它跟踪到异常发生在某个类的第几行,这对我们非常有用。但是我们有时只想得到这些 StackTrace数据,通过其它方式表现出来(非控制台,如网页或GUI),这就有了这篇文章.回想一下,原来的日志工具log4、weblogic服务器、还有webshpere服务器等等好像都可以得到这些信息,所以就先直接在Exception类找找有没有直接的方法可以返回这些信息,看到getStackTrace()方法返回一个StackTraceElement对象的集合(原来怎么没注意到呢?),翻一下JDK,一看StackTraceElement类提供的方法(
String
getFileName()
Returns the name of the source file containing the execution point represented by this stack trace element.
int
getLineNumber()
Returns the line number of the source line containing the execution point represented by this stack trace element.
String
getMethodName()
Returns the name of the method containing the execution point represented by this stack trace element.
int
hashCode()
Returns a hash code value for this stack trace element.
boolean
isNativeMethod()
Returns true if the method containing the execution point represented by this stack trace element is a native method.
String
toString()
)没错,就是他了,写段代码测试一下先:public static void main(String[] args) {
try{
byte[] a=args[0].getBytes();
}catch (Exception ex){
ex.printStackTrace();
StackTraceElement [] messages=ex.getStackTrace();
int length=messages.length;
for(int i=0;i<length;i++){
System.out.println("ClassName:"+messages[i].getClassName());
System.out.println("getFileName:"+messages[i].getFileName());
System.out.println("getLineNumber:"+messages[i].getLineNumber());
System.out.println("getMethodName:"+messages[i].getMethodName());
System.out.println("toString:"+messages[i].toString());
}
}
}
2.
import java.io.PrintWriter;
import java.io.StringWriter;
public class PrintWriterTest {
public static void main(String[] args) {
try{
Exception ex = new Exception("aaa");
throw ex;
}catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
System.out.println("*****="+sw.getBuffer().toString());
}
}
}
- 打印异常信息 方法汇总
- python 打印异常信息
- 打印Java异常信息
- python 打印异常信息
- 打印异常信息
- elasticsearch异常信息汇总
- elasticsearch异常信息汇总
- java 异常信息详细打印
- sqlite数据库异常汇总信息
- Javascript网页打印方法汇总
- Javascript网页打印方法汇总
- JSP 500页面的异常信息打印
- JAVA中打印出异常信息
- Struts2配合Log4j打印异常栈信息
- struts2配合log4j打印异常栈信息
- java打印异常中的堆栈信息
- struts2配合log4j打印异常栈信息
- 打印未知异常的提示信息
- 最近在项目中遇到的几个小小问题
- Delphi中初始化.Ini文件的读写
- 二值图像连通域标记算法与代码
- 移植U-BOOT到扬创2440心得
- 子进程中执行程序
- 打印异常信息 方法汇总
- QQ聊天
- MySql数据库基本操作
- csdn我的天地开通
- 今天听到的一个好消息和一个坏消息
- HttpWebRequest提交Form和上传文件的认证问题
- 不用输入用户名,让系统自动登陆
- 一个不错的 java初学者手册
- 正确理解和判断PR劫持的方法(站长必看)