-------
android培训、
java培训、期待与您交流! ----------
Java在运行时发生异常,会生成个异常类对象,可以用try{}catch{}来捕获异常
在catch语句中可以使用这个对象的一些方法来捕获这些信息,如:
getMessage() 得到异常的有关信息
printStackTrace() 用来跟踪异常事件发生时执行堆栈的内容
在方法定义中可以通过throws来抛出异常给上一层,在方法体内抛出异常用throw
异常的分类:
所有的异常类的基类是Throwable,它有俩个子类 Error和Exception,其中Error是系统的内部错误,是虚拟机的错误,程序是处理不了的,Exception是我们可以处理的异常,在Exception里面有RuntimeException,RuntimeException是经常出现的错误,可以去逮它,也可以不逮它,如除数不能为零,数组下标越界的这种异常,而Exception除了RuntimeException异常外的其它异常,都必须在程序中去逮它,在API文档中的那些有throws的类都抛出这类异常
finally语句在try catch 语句后面,无论产不产生异常都执行,是异常的处理统一的出口
自定义的异常:
//自定义异常
public class LookhanExcepiton extends Exception {
public int day;
public LookhanExcepiton(String message,int day){
super(message);
this.day = day;
}
public int getDay(){
return this.day;
}
}
/**
* 自定义异常
* @author http://www.lookhan.com
*
*/
public class TestExcepiton {
public static void main(String[] args) {
int day = 35;
TestExcepiton test = new TestExcepiton();
try {
test.come(day);
} catch (LookhanExcepiton e) {
e.printStackTrace();
System.out.println("天数:" + e.getDay());
}
}
public void come(int day) throws LookhanExcepiton{
if(day > 30){
LookhanExcepiton exception = new LookhanExcepiton("你已经超过一个月没报错了",day);
throw exception;
}
}
}