exception 类 java_关于Java中Exception类的一些方法

序:这篇文章我其实不知道取什么标题好,之前写了一篇文章,关于Android调试时打印的一些技巧,但是其中犯了个比较低级的错误(其实也不是说错误,就是代码中反而自己绕了远路),经一位朋友的及时指正,而问题也能够有更好的方法解决,该文章就没有再存在的必要。

但是其中主要涉及的Exception的一些方法,应该还是有一定的作用,故而有此文。

废话至此,切入正题。

Java中的Exception异常类是我们程序中常见的一个类,在处理异常时我们经常使用printStackTrace()来打印异常信息。下面看一个异常的例子和打印信息:

packagecom.kofi.ept;/***@authorKofi

**/publicclassMainTest {publicstaticvoidmain(String[] args){

Test test=newTest();

test.print1();

}

}classTest {publicvoidprint1(){

print2();

}publicvoidprint2(){int[] array=newint[5];try{

array[5]=4;

}catch(Exception e) {

e.printStackTrace();

}

}

}

在print2方法里我们制造了一个数组越界异常,看一下打印信息:

03d998b30c1313980401e6549b1bb5db.png

可以发现,会打印出异常产生的地方(print2方法)及调用它的print1直到main的信息。

Exception还有一个getStackTrace()方法,返回类型是一个StackTraceElement数组,该方法的解释如下:

Returns an array of stack trace elements, each representing one stack frame. The zeroth element of the array (assuming the array's length is non-zero) represents the top of the stack, which is the last method invocation in the sequence. Typically, this is the point at which this throwable was created and thrown. The last element of the array (assuming the array's length is non-zero) represents the bottom of the stack, which is the first method invocation in the sequence.

小白我英文不好,反正大概意思就是说返回的是一个栈,0位置的是最后的方法(也就是异常所处的代码行所在方法),然后往上……,也就是想上面打印出的异常信息那样的顺序。

getFileName()

getClassName()

getMethodName()

getLineNumber()

这个看方法名就知道什么意思了。

利用这点,我们可以主动构造一个异常类,来打印追踪程序中的调用层次信息。

我们把print2方法改为如下:

publicvoidprint2(){

StackTraceElement[] st=newException().getStackTrace();

System.out.println("FileName\tClassName\t\tMethodName\tLineNumber\n");for(inti=0; i

System.out.print(st[i].getFileName()+"\t");

System.out.print(st[i].getClassName()+"\t");

System.out.print(st[i].getMethodName()+"\t\t");

System.out.print(st[i].getLineNumber()+"\n");

}

}

打印信息如下:

345e1891550f4a6d329fc61ef638d074.png

所以之前的异常信息也就是如此。

OK,差不多了,就是这些东西,具体有什么用处,大家自己看着办吧。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值