异常

来源:互联网 发布:微信ubuntu版 编辑:程序博客网 时间:2024/05/16 11:24
一、Java中异常的分类:

所有异常,都继承自java.lang.Throwable类,它有两个直接子类,Error类和Exception类。

Exception是任何标准Java库的类方法,自己的方法以及运行时任何异常中抛出来的基类型。异常可分为执行异常(RuntimeException)和检查异常(CheckedExceptions)两种。需要检查抛出的一般是检查异常(Checked Exceptions)。

The Throwable class is the superclass of all errorsand exceptions in the Java language. Only objects that areinstances of this class (or one of its subclasses) are thrown bythe Java Virtual Machine or can be thrown by the Javathrow statement. Similarly, only this class or one ofits subclasses can be the argument type in a catchclause.

二、个人认为,Exception类是java最具多态性的类之一。因为它的direct knownsubclasses千千万,catch方法传入的参数难道要每类都写清楚么?反正本人从来只写catch(Exceptione),然后在方法体中,让它自由飞翔。。。

三、try catch finally好基友一起走。

四、对于所有IO的关闭,放在finally代码块中是最为合适的。

五、自建RuntimeException异常的一个例子,用来抛出年龄为负的异常。

if(age < 0) {

  RuntimeException re = newRuntimeException("Age can't be negative");

  throw re;

}

RuntimeException编译过程没问题,会在运行过程中抛出异常。

如果在这里自建的是一个Exception也就是Checked Exception,如:

if(age < 0) {
   Exception e = newException("年龄不能为负数");
   throw e;
}

则在编译中就会报错:

UserE.java:8: error: unreported exception Exception; must becaught or declared
to be thrown
  throw re;
  ^

这样除了用try catch来捕捉外,还可以用throws来声明异常。eg:

public void setAge(int age) throws Exception {
if(age < 0) {
Exception e = new Exception("年龄不能为负数");
throw e;
}
  this.age = age;
}

这样这个class在编译的时候就不会报错,throws关键字的作用在于将这个异常转交给调用该方法的类。调用包含throws关键词方法时,要用try catch对其异常进行捕捉,否则编译过程中会报错。

原创粉丝点击