java 异常
JAVA 异常处理 0... 异常的层次结构 Object->Throwable->Exception(所有异常类的父类) 异常:程序运行过程中的错误 { 1、逻辑错误 2、输入错误 3、物理错误 } 1.... try {..}catch(Exception e){..} 比如下面的一个案例: public class ExceptionTest{ public int devide(int x,int y){ return x/y; } public static void main(String[] agrs){ ExceptionTest e=new ExceptionTest(); System.out.println(e.devide(3,0)); } } ->上面的这段程序 因为y=0了,这是算数错误是会报异常的。 但是为了不是程序中止,我们可以使用try{}catch{}语句 public class ExceptionTest{ public int devide(int x,int y){ return x/y; } public static void main(String[] agrs){ ExceptionTest e=new ExceptionTest(); try{ System.out.println(e.devide(3,0)); }catch(Exception e){ System.out.println(e.getMessage()); System.out.println("程序出现了算数错误,请查证。。"); } } } ->这样的话,程序在出现异常后,也能正常的运行,没有异常中止 ->其中try是用来捕获异常的,而catch是用来处理异常的 捕获到错误时,跳到catch块 2.... finally关键字 ->也有在try..catch..后面再加上finally的 不管前面是否捕获异常,都是会执行finally这个块的 public class ExceptionTest { public static void main(String[] args) { try{ System.out.println("...."); return;//这里是测试的关键 }catch(Exception e){//其实即便出现了异常,执行了catch语句,下面的finally也是会执行了 System.out.println(e.getMessage()); }finally{//这个是无论如何都是会被执行的 System.out.println("这个还是被执行了"); } System.out.println("kkk");//由于在try的时候,就已经return了,所以这个是不会被执行的 } } //程序输出的结果是: try.. fianlly语句还是被执行了 3.... throws关键字 class ExceptionTest { public void show() throws Exception{//这里是有作出抛出异常的 System.out.println("这是一个测试而已!"); } } //下面的这个类调用了上面类中的方法,因为上面的方法是有抛出异常的 public class Exception1 { public static void main(String[] args) throws Exception { ExceptionTest e=new ExceptionTest(); e.show();//这里这样是不行的,必须对异常作出处理 使用try..catch。。或抛出 //我们这里直接抛出好了就是上面的 throws Exception } } ->这样子程序就能够编译成功了!因为先前写的类可能是由不同的人使用的,可能不止是否会有异常的 ->情况出生,所以public void show() throws Exception 就相当于告知使用者必须进行处理 ->但是要注意的是,这种在main中的抛出,一旦出现异常也是会异常终止的 4... 自定义的异常 & Throw关键字 //自定义异常 -> 这个异常类继承与Exception或及其子类 //AgeErrorException -> Exception public class AgeErrorException extends Exception{//异常类继承与Exception public static final int errId=1;//错误的编号 public AgeErrorException(String msg){//传进来一个信息 用于输出 super(msg); } public AgeErrorException(){ super("错误编号:"+errId+"\t年龄输入错误,请订正..."); } } public class Person { private int age; private String name; public void setAge(int age) throws Exception { //多态 Exception -> AgeErrorException if(age<0){//以面向对象的方式来处理异常 // throw new AgeErrorException("lalalal...."); //有指定信息的错误类 throw new AgeErrorException(); //默认输出的错误类 手动抛出异常对想 }else{ this.age = age; } } public Person() { super(); } public Person(int age, String name) { super(); this.age = age; this.name = name; } public int getAge() { return age; } public String getName() { return name; } public void setName(String name) { this.name = name; } } public class Test { public static void main(String[] args) { Person p=new Person(); p.setName("yht"); try { p.setAge(-12); //如果这里出现了异常,就抛出异常 由catch中的语句进行处理 } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }