您的位置:首页 > 编程语言 > Java开发

Java的异常机制详解

2006-09-25 19:14 716 查看
 说在前面:
想深入了解异常机制的话,好好读读JDK document中Throwable, Error, Exception类的Java doc.

言归正传:
Java中的异常机制是指程序运行时出现的exceptional situation;异常机制的完成是通过Throwable类实现的。
(而不是直观上认为的,异常机制仅仅和Exception类相关)
Java中的Trowable类有两个子类,Error, Exception. Exception有很多子类,其中有一个是RuntimeException.
他们代表了程序运行过程中,出现的影响程序运行的情况。
Error, Exception都是可以捕获的。其中,Error是程序运行过程中abnormal condition,是推荐不要捕获的;RuntimeException是程序运行过程中经常出现的错误情况,是可以不捕获的;而其他的Exception是必须要捕获的。
如果出现了这样的影响程序正常运行的情况,而没有捕获的话,函数就会终止运行,把异常抛给调用该函数的上一级函数。直到出现包含错误处理(catch)的层。
如果,该线程所有的调用层次上都没有异常处理。那么,就会终止该线程的运行。

Throwable类的Java doc.
"
The Throwable class is the superclass of all errors and exceptions in the Java language. Only objects that are instances of this class (or one of its subclasses) are thrown by the Java Virtual Machine or can be thrown by the Java throw statement. Similarly, only this class or one of its subclasses can be the argument type in a catch clause.

Instances of two subclasses, Error and Exception, are conventionally used to indicate that exceptional situations have occurred. Typically, these instances are freshly created in the context of the exceptional situation so as to include relevant information (such as stack trace data).

... ...
"

说在后面:  
Java用了快3年了,其中的Exception机制也用了快3年了。
也曾经做过试验专门的研究其中的机制。
但直到今天才算真正了解其中的细节(现在说这话,有点不太自信了;以前也是认为自己已经完全明白Java的异常机制是怎么回事)。

1 错误的试验,错误的结论害死人
2 权威的参考一定要硬着头皮,把它读懂。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息