Java常见的异常,Java运行时异常和一般异常的区别

来源:互联网 发布:云计算架构师是干嘛的 编辑:程序博客网 时间:2024/05/16 08:34

Java常见的异常,Java运行时异常和一般异常的区别




异常和错误二者的不同之处:



Exception:

1.可以是可被控制(checked,检查异常) 或不可控制的(unchecked,非检查异常)。
2.表示一个由程序员导致的错误。
3.应该在应用程序级被处理。


JavaDoc:RuntimeException and its subclasses are unchecked exceptions. Unchecked exceptions do not need to be declared in a method or constructor's throws clause if they can be thrown by the execution of the method or constructor and propagate outside the method or constructor boundary.

原则:

引用某个人的话:几乎在所有的情况下都不应当使用检查型异常。当遇到检查型异常无法处理的情况时,应该使用异常转译转换为非检查型异常再抛出。(原作者不明) 在Think in Java 4th Edition上作者对这样的观点进行了详细的描述。



Error:

1.总是不可控制的(unchecked,(广义上的)非检查异常)。
2.经常用来用于表示系统错误或低层资源的错误。

3.如何可能的话,应该在系统级被捕捉。

JavaDoc:  An Error is a subclass of Throwable that indicates serious problems that a reasonable applicationshould not try to catch.

Error and its subclasses are regarded as unchecked exceptions for the purposes of compile-time checking of exceptions.


可检查异常经编译器验证,对于声明抛出异常的任何方法,编译器将强制要求进行异常处理。

为什么Error子类属于非检测异常?这是因为无法预知它们的产生时间。若Java应用程序内存不足,则随时可能出现OutOfMemoryError;起因一般不是应用程序中的特殊调用,而是JVM自身的问题。另外,Error类一般表示应用程序无法解决的严重问题,故将这些类视为非检查异常。编译器不强制要求编写异常处理代码。

RuntimeException即运行时异常,属于非检查异常,它们表示的问题不一定需要异常处理。可以在try-catch结构中处理NullPointerException,但若在使用引用前测试空值,则更简单,更经济。同样,可以在除法运算时检查0值,而不使用ArithmeticException。

0 0
原创粉丝点击