常见异常和异常处理

编译异常:可以人为处理,eclipse和idea也会提示

运行时异常:

NullpoiontException  空指针异常

例:对象为null

List<String> list = null; 

list.add("123");

ArrayIndexOutOfBoundsException 数组下标越界异常

例:

String[] str = { "123", "456" };

System.out.println(str[3]);//数组str下标最大为1

ArithmeticException 除数为0时

例:

System.out.println(10 / 0);

异常处理:

try catch捕获异常

在 finally 代码块中,可以运行清理类型等收尾善后性质的语句。

 例:

try {

file = new FileInputStream(fileName);

x = (byte) file.read();

} catch(FileNotFoundException f) { // Not valid!

f.printStackTrace();

return -1;

} catch(IOException i) {

i.printStackTrace();

return -1;

}

异常方法

下面的列表是 Throwable 类的主要方法:

序号 方法及说明
1 public String getMessage()
返回关于发生的异常的详细信息。这个消息在Throwable 类的构造函数中初始化了。
2 public Throwable getCause()
返回一个Throwable 对象代表异常原因。
3 public String toString()
使用getMessage()的结果返回类的串级名字。
4 public void printStackTrace()
打印toString()结果和栈层次到System.err,即错误输出流。
5 public StackTraceElement [] getStackTrace()
返回一个包含堆栈层次的数组。下标为0的元素代表栈顶,最后一个元素代表方法调用堆栈的栈底。
6 public Throwable fillInStackTrace()
用当前的调用栈层次填充Throwable 对象栈层次,添加到栈层次任何先前信息中。

猜你喜欢

转载自www.cnblogs.com/nxjblog/p/10612331.html