异常机制

异常

分类 Error+RuntimeException为未检查异常其他为已检查异常

(程序错误引起的叫未检查异常-----因为未检查代码所导致的异常????)

必须声明所有的已检查异常,但不可声明抛出未检查异常。

未检查异常要么不可控(Error类),要么应该避免发生(RuntimeException类)

异常在继承问题上的两个注意点:

Ø  子类声明的已检查异常不能超出超类声明的异常范围

Ø  超类方法没有抛出任何已检查异常,子类也不能抛出任何已检查异常。

抛出异常

Throw new EOFException();

创建异常类

最主要的是要覆盖两个构造函数,

Throwable()

Constructs a new throwable with null as its detail message.

 

Throwable(String 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.

还有一个详细信息方法

String

getMessage()

Returns the detail message string of this throwable.

 

异常栈类

StackTraceElement[]

getStackTrace()

Provides programmatic access to the stack trace information printed by printStackTrace().

 

StackTraceElement类

String

getClassName()

Returns the fully qualified name of the class containing the execution point represented by this stack trace element.

String

getFileName()

Returns the name of the source file containing the execution point represented by this stack trace element.

int

getLineNumber()

Returns the line number of the source line containing the execution point represented by this stack trace element.

String

getMethodName()

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核心技术卷一》

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值