异常

一、Java中异常的分类:

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

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

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.

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

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

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

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

if(age < 0) {

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

  throw re;

}

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

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

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

则在编译中就会报错:

UserE.java:8: error: unreported exception Exception; must be caught 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对其异常进行捕捉,否则编译过程中会报错。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值