异常
分类 Error+RuntimeException为未检查异常其他为已检查异常
(程序错误引起的叫未检查异常-----因为未检查代码所导致的异常????)
必须声明所有的已检查异常,但不可声明抛出未检查异常。
未检查异常要么不可控(Error类),要么应该避免发生(RuntimeException类)
异常在继承问题上的两个注意点:
Ø 子类声明的已检查异常不能超出超类声明的异常范围
Ø 超类方法没有抛出任何已检查异常,子类也不能抛出任何已检查异常。
抛出异常
Throw new EOFException();
创建异常类
最主要的是要覆盖两个构造函数,
Constructs a new throwable with null as its detail message. | |
| Constructs a new throwable with the specified detail message. |
| Throwable(String message, Throwable cause) //???? Constructs a new throwable with the specified detail message and cause. |
还有一个详细信息方法
Returns the detail message string of this throwable. |
异常栈类
Provides programmatic access to the stack trace information printed by printStackTrace(). |
StackTraceElement类
Returns the fully qualified name of the class containing the execution point represented by this stack trace element. | |
Returns the name of the source file containing the execution point represented by this stack trace element. | |
int | Returns the line number of the source line containing the execution point represented by this stack trace element. |
Returns the name of the method containing the execution point represented by this stack trace element. |
另一个方法:Thread.getAllStackTrace()
Catch中的包装技术
如果在一个方法中发生了一个已检查异常,而不允许抛出它,那么包装技术就十分有用。
Try{
}
Catch(SQLException e)
{
Throwablese = new ServletException(“database error”);
Se.initCause(e);
Throwse;
}
捕获到异常后需要 Throwable e = se.getCause();
Try/catch try/finally
为了解决无法报告finally语句的错误而设计的一种新的异常机制。
Try
{
Try{
//1
}finally{
In.close();//2
}
}catch{
}
问题:1处发生异常exception1 2处发生exception2
则 2处的异常将覆盖1处的异常。
注意:在try语句中执行return
Finally的语句依然被执行,如果finally语句中也有一个return,上一个return将被覆盖。
几个关于异常使用的建议:
Ø 异常不能代替简单的测试(if测试)
Ø 不要过分地细化异常。
Ø 不要压制异常,要敢于抛出
Ø 检测出错误时,对异常要“苛刻”P486《Java核心技术卷一》