得到java异常printStackTrace的详细信息

平时写java代码时,想看抛出的异常信息,来找出具体的异常点,我们常常会用Exception.toString ()或者 Exception.getMessage()来取得异常信息,再把它print到控制台,,但是这些信息只能告诉我们异常本身的信息,对我们找出异常点帮助并不太理想,所以我们会使用Exception.printStackTrace()方法,这样就可以在控制台输出非常详细的异常信息,甚至可以通过它跟踪到异常发生在某个类的第几行,这对我们非常有用。但是我们有时只想得到这些 StackTrace数据,通过其它方式表现出来(非控制台,如网页或GUI),这就有了这篇文章.回想一下,原来的日志工具log4、weblogic服务器、还有webshpere服务器等等好像都可以得到这些信息,所以就先直接在Exception类找找有没有直接的方法可以返回这些信息,看到getStackTrace()方法返回一个StackTraceElement对象的集合(原来怎么没注意到呢?),翻一下JDK,一看StackTraceElement类提供的方法(

 
StringgetFileName() 
          Returns the name of the source file containing the execution point represented by this stack trace element.
 intgetLineNumber() 
          Returns the line number of the source line containing the execution point represented by this stack trace element.
 StringgetMethodName() 
          Returns the name of the method containing the execution point represented by this stack trace element.
 inthashCode() 
          Returns a hash code value for this stack trace element.
 booleanisNativeMethod() 
          Returns true if the method containing the execution point represented by this stack trace element is a native method.
 StringtoString()
)没错,就是他了,写段代码测试一下先:

[java]  view plain  copy
  1. public static void main(String[] args) {  
  2.   try{  
  3.    byte[] a=args[0].getBytes();  
  4.      
  5.   }catch (Exception ex){  
  6.      
  7.    ex.printStackTrace();  
  8.    StackTraceElement [] messages=ex.getStackTrace();  
  9.    int length=messages.length;  
  10.    for(int i=0;i<length;i++){  
  11.     System.out.println("ClassName:"+messages[i].getClassName());  
  12.     System.out.println("getFileName:"+messages[i].getFileName());  
  13.     System.out.println("getLineNumber:"+messages[i].getLineNumber());  
  14.     System.out.println("getMethodName:"+messages[i].getMethodName());  
  15.     System.out.println("toString:"+messages[i].toString());  
  16.     }  
  17.    }  
  18.  }  

Ok,秘密找到了,原来就这么回事。

以上内容转自:http://blog.csdn.net/haiquan968/article/details/4619737

下面自己写了一个得到异常详细信息的方法

[java]  view plain  copy
  1. public String getExceptionDetail(Exception e) {  
  2.         StringBuffer stringBuffer = new StringBuffer(e.toString() + "\n");  
  3.         StackTraceElement[] messages = e.getStackTrace();  
  4.         int length = messages.length;  
  5.         for (int i = 0; i < length; i++) {  
  6.             stringBuffer.append("\t"+messages[i].toString()+"\n");  
  7.         }  
  8.         return stringBuffer.toString();  
  9.     }  
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值