异常
来源:互联网 发布:微信ubuntu版 编辑:程序博客网 时间:2024/05/16 11:24
所有异常,都继承自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 catch
clause.
二、个人认为,Exception类是java最具多态性的类之一。因为它的direct knownsubclasses千千万,catch方法传入的参数难道要每类都写清楚么?反正本人从来只写catch(Exceptione),然后在方法体中,让它自由飞翔。。。
三、try catch finally好基友一起走。
四、对于所有IO的关闭,放在finally代码块中是最为合适的。
五、自建RuntimeException异常的一个例子,用来抛出年龄为负的异常。
if(age < 0) {
}
RuntimeException编译过程没问题,会在运行过程中抛出异常。
如果在这里自建的是一个Exception也就是Checked Exception,如:
if(age < 0) {
}
UserE.java:8: error: unreported exception Exception; must becaught or declared
to be thrown
这样除了用try
public void setAge(int age) throws Exception {
if(age < 0) {
Exception e = new Exception("年龄不能为负数");
throw e;
}
}
这样这个class在编译的时候就不会报错,throws关键字的作用在于将这个异常转交给调用该方法的类。调用包含throws关键词方法时,要用try
- 异常
- 异常!
- 异常
- 异常
- 异常
- 异常
- 异常
- 异常
- 异常
- 异常
- 异常
- 异常
- 异常
- 异常
- 异常
- 异常
- 异常
- 异常
- 6.6总结:多态,抽象,包和权限
- 接口和简单静态工厂方法模式
- 转:UTF8与UTF8 without&nbsp…
- 转:java 匿名类(不能被忽略…
- 转:java synchronized详解
- 异常
- java基础数据类型拾遗
- 转:java.math.BigDecimal类的用法
- BigDecimal使用注意
- Visual Studio中的各种工程属性设置经验
- 转:驯服 Tiger: 深入研究枚举类型
- IO和Decorator模式
- 开始慢慢转到51cto
- 在Python中判断字符为数字还是字母