第9章-异常:
创建异常:和 Java 的其他任何对象一样,需要用 new 在内存堆里创建违例,并需调用一个构建器
if(t == null)
throw new NullPointerException("t = null");
用一个try关键字开头:
try {
// Code that might generate exceptions
} catch(Exception e) {
// Handle exceptions of Type1
}
String toString()
返回对 Throwable 的一段简要说明,其中包括详细的消息(如果有的话)。
void printStackTrace()
void printStackTrace(PrintStream)
打印出 Throwable 和 Throwable 的调用堆栈路径。调用堆栈显示出将我们带到违例发生地点的方法调用的顺序。
抛出异常:
catch(Exception e) {
System.out.println("一个异常已经产生");
throw e;//抛出异常
}
if(t == null)
throw new NullPointerException("t = null");
自定义异常:
class MyException extends Exception{
public MyException(){}
public MyException(String msg){
super(msg)
}
}
finally可以帮助程序释放资源,finally语句总会被执行、尽量不要在finally语句中编写return、抛出异常相关代码
try{
//dosomething
}finally{
close();
}