您的位置:首页 > 编程语言 > Java开发

关于Java中Exception类的一些方法

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

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

废话至此,切入正题。

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

package com.kofi.ept;

/**

* @author Kofi

*

*/

public class MainTest {

public static void main(String[] args){

Test test = new Test();

test.print1();

}

}

class Test {

public void print1(){

print2();

}

public void print2(){

int[] array = new int[5];

try{

array[5] = 4;

}catch (Exception e) {

e.printStackTrace();

}

}

}


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





可以发现,会打印出异常产生的地方(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位置的是最后的方法(也就是异常所处的代码行所在方法),然后往上……,也就是想上面打印出的异常信息那样的顺序。

StackTraceElement有下面一些方法:

getFileName()

getClassName()

getMethodName()

getLineNumber()

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

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

我们把print2方法改为如下:

public void print2(){

StackTraceElement[] st = new Exception().getStackTrace();

System.out.println("FileName\tClassName\t\tMethodName\tLineNumber\n");

for (int i = 0; i < st.length; 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");

}

}


打印信息如下:





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

OK,差不多了,就是这些东西,具体有什么用处,大家自己看着办吧。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: