现在的位置: 首页 > 综合 > 正文

java 异常 错误

2018年01月26日 ⁄ 综合 ⁄ 共 1537字 ⁄ 字号 评论关闭

Error: Any departure from the expected behavior of the system or program, which stops the working of the system is an error. 

Exception:Any error or problem which one can handle and continue to work normally.


Note that in Java a compile time error is normally called an "error," while a runtime error is called an "exception."
Errors don't have subclasses while exception has two subclasses, they are compile time exception or checked exception (ClassNotFound Exception, IOException,
SQLException etc.) and runtime or unchecked exception(ArrayIndexOutOfBounds Exception, NumberFormat Exception).

Error类和Exception类都继承自Throwable类。

Error的继承关系:

Exception的继承关系:

二者的不同之处:

Exception:

1.可以是可被控制(checked) 或不可控制的(unchecked)。

2.表示一个由程序员导致的错误。

3.应该在应用程序级被处理。

Error:

1.总是不可控制的(unchecked)。

2.经常用来用于表示系统错误或低层资源的错误。

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

Java 中定义了两类异常:

1) Checked exception: 这类异常都是Exception的子类 。异常的向上抛出机制进行处理,假如子类可能产生A异常,那么在父类中也必须throws A异常。可能导致的问题:代码效率低,耦合度过高。

2) Unchecked exception: 这类异常都是RuntimeException的子类,虽然RuntimeException同样也是Exception的子类,但是它们是非凡的,它们不能通过client code来试图解决,所以称为Unchecked exception 。

Java中用2种方法处理异常:

1.在发生异常的地方直接处理;

2.将异常抛给调用者,让调用者处理。

Java异常可分为3种:

  (1)编译时异常:Java.lang.Exception

  (2)运行期异常:Java.lang.RuntimeException

  (3)错误:Java.lang.Error

Java.lang.Exception和Java.lang.Error继承自Java.lang.Throwable;

Java.lang.RuntimeException继承自Java.lang.Exception.

编译时异常: 程序正确,但因为外在的环境条件不满足引发。例如:用户错误及I/O问题----程序试图打开一个并不存在的远程Socket端口。这不是程序本身的逻辑错误,而很可能是远程机器名字错误(用户拼写错误)。对商用软件系统,程序开发者必须考虑并处理这个问题。Java编译器强制要求处理这类异常,如果不捕获这类异常,程序将不能被编译。

运行期异常: 这意味着程序存在bug,如数组越界,0被除,入参不满足规范.....这类异常需要更改程序来避免,Java编译器强制要求处理这类异常。

错误: 一般很少见,也很难通过程序解决。它可能源于程序的bug,但一般更可能源于环境问题,如内存耗尽。错误在程序中无须处理,而有运行环境处理。

抱歉!评论已关闭.