---恢复内容开始---数据库
异常的概述和分类
Throwable类是Java语言中全部错误或者异常的超类(也就是说,Java中全部的报错都是继承与Throwable的),也只有当对象是此类或者此类的子类的实例之一时,才可以经过Java虚拟机或者Javathrow语句进行抛出。数组
main函数收到异常的时候,会有两种处理方式:服务器
1.本身将该错误处理,让后继续执行代码jvm
2.本身没有针对的处理方式,只有将其交给main的jvm来处理ide
JVM有一个默认的异常处理机制,就将该异常进行处理,并将该异常的名称、异常的信息、异常出现的位置打印在控制台上,同时程序中止运行。函数
咱们使用try...catch...finally...来捕获异常,而后呢,能够继续执行咱们的代码this
可是呢,咱们使用throw抛出异常的话就会结束程序了spa
catch(能够写多个错误类名){} 固然咱们也能够是定义多个catch指针
注意:全部的RuntimeException类及其子类的实例被称为运行是异常,其余异常就是编译时异常code
编译是异常:
运行时异常:
Exception是一个继承Throwable的子类
Throwable有几个经常使用的方法:
package null0801_2026; public class Demo01 { public static void main(String[] args) throws Exception { // TODO Auto-generated method stub Student std = new Student(11,"n1"); std.setAge(11); } } class Student{ private int age; private String name; public int getAge() { return age; } public void setAge(int age) throws Exception { if(age>10){ throw new Exception("不能大于10"); }else{ this.age = age; } } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Student [age=" + age + ", name=" + name + "]"; } public Student() { super(); // TODO Auto-generated constructor stub } public Student(int age, String name) { super(); this.age = age; this.name = name; } }
throw的使用场景:
在方法内部出现某种状况,程序不能继续执行,就用throw把异常对象抛出
thorws:
thorw:
特色:
finally咱们通常用于IO流操做中的释放资源
1.final能够修饰类-表示不能被继承,能够修饰方法-表示不能被重写,修饰变量-表示只能赋值一次 2.finally是try语句中的一个语句体,不能单独使用,通常咱们用做IO中的释放资源 3.finalize是一个方法,当垃圾回收器肯定不存在对该对象的更多引用的时候,由对象的垃圾回收器调用此方法。
原则:若是本身能处理的问题就本身解决(try...catch),若是不能解决,就throws
如何自定义一个异常?例子:
package null0801_2026; public class AgeError extends RuntimeException{ public AgeError() { super(); // TODO Auto-generated constructor stub } public AgeError(String arg0, Throwable arg1, boolean arg2, boolean arg3) { super(arg0, arg1, arg2, arg3); // TODO Auto-generated constructor stub } public AgeError(String arg0, Throwable arg1) { super(arg0, arg1); // TODO Auto-generated constructor stub } public AgeError(String arg0) { super(arg0); // TODO Auto-generated constructor stub } public AgeError(Throwable cause) { super(cause); // TODO Auto-generated constructor stub } }