1.异常:异常就是Java程序正在运行过程中出现的错误
2. 两种处理异常的方式:try catch,throws
3.Throwable子类有Error,Exception; Exception子类有RuntimeException(运行时异常)等等...
4. try catch finally 处理异常
try用来检测异常,catch用来捕获异常,finally用来释放资源
5.throws的方式处理异常
throw:在功能方法内部出现某种情况,程序不能继续运行,需要跳转时,就用throw把异常对象抛出
throw与throws的区别:
throw:用在方法体内,跟的是异常对象名;只能抛出一个异常对象名;表示抛出异常,有方法体内的语句处理
throws:用在方法声明后面,跟的是异常类名;可以跟多个异常类名,由逗号隔开;表示抛出异常,由该方法的调用者来处理
6.编译时异常的抛出,必须对其进行处理,运行时异常的抛出可以处理也可以不处理
7.finally:被finally控制的语句体一定会执行;在执行到finally之前jvm退出了就不会执行(System.exit(0))
用于释放资源,比如,在IO流操作和数据库操作
8.自定义异常:取决于它的名字,为了通过名字区分到底是什么异常,然后有针对的解决方法
9.异常类注意事项:1.子类重写父类方法时,子类的方法必须抛出相同的异常或父类异常的子类; 2.如果父类抛出了多个异常, 子类重写父类时,只能抛出相同的异常或者是它的子集,子类不能抛出父类没有的异常;3.如果被重写的方 法没有异常抛出,那么子类的方法绝对不可以抛出异常,如果子类方法内有异常发生,那么子类只能try,不能throws
10.如果该功能内部可以将问题处理,用try,如果处理不了,交由调用者处理,这是用throws
11.区别:后续程序需要运行和就用try,不需要继续运行就throws
12.alt+shift+z try catch的快捷键
package pra_14;
public class J_28 {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
Div div=new Div();
try{ //检测可能会发生问题的代码
int x=div.div(2, 1);
System.out.println(x);
}catch(ArithmeticException a){ //ArithmeticException a=new ArithmeticException();
System.out.println("除数不能为0!");
}finally{
System.out.println("hello");
}
//try...catch的方式处理多个异常,处理多个异常时,根据多态的原理,小的异常放在前面
int a=10;
int b=0;
int[] arr={11,22,33,44};
try{
//System.out.println(a/b);
//System.out.println(arr[10]);
}catch(ArithmeticException ar){
System.out.println("除数不能为零!");
}catch(ArrayIndexOutOfBoundsException array){
System.out.println("索引越界!");
}catch(Exception e){
System.out.println("出错~");
}
//throws的方式处理异常
People p=new People();
p.setAge(-17);
System.out.println(p.getAge());
}
}
class People{
private String name;
private int age;
public People() {
super();
}
public People(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) throws AgeOutException {
if(age>0&&age<150){
this.age = age;
}
else{
throw new AgeOutException("年龄非法!");
//throw new Exception("年龄出错了!");
}
}
}
//自定义异常类
class AgeOutException extends Exception{
public AgeOutException() {
super();
}
public AgeOutException(String message) {
super(message);
}
}
class Div{
public int div(int a, int b){
return a/b;
}
}