异常的概念异常是在程序的运行过程中发生的异常事件,例如打开一个不存在的文件、网络连接中断、数组下标越界、正在加载的类文件丢失等都会引发异常。
class ExceptionDemo{ public static void main(String[] args){ int[] a=new int[5]; a[10]=10; //此处将会发生数组下标越界的异常 } }
java中的异常类可分为两大类:ErrorException
异常的处理Java中的错误类(Error)定义了程序中不能恢复的严重错误条件。如内存溢出、类文件格式错误等。这一类错误由Java运行系统处理,不需要我们去处理。Java中的异常类(Exception)定义了程序中遇到的轻微的错误条件,在可能出现异常的地方,运用try/catch/finally语句处理。 try{ 可能产生异常的语句 } catch (Exception1 e) { 出了第一种异常怎么办? } catch (Exception2 e) { 出了第二种异常怎么办? } finally{ 不论怎样都会执行的语句,通常包括释放一些资源的语句 }class Excep{ public int division(int a,int b){ return a/b; }}class ExcepDemo{ public static void main(String[] args){ Excep excep=new Excep(); try{ excep.division(5,0); //可能发生异常的语句 }catch(Exception e){ System.out.println("除数不能为0!"); }finally{ System.out.println(“finally语句块执行!”); //finally中的内容始终会执行 } System.out.println("程序执行完毕!"); }}
多重catch块的注意事项当有多个catch语句的时候,如果执行了其中一个catch语句,则其他catch语句将不再执行;
父类异常不能放入前面的catch块中,例如: try{ int i=5/0; }catch(Exception e){ //错误,父类异常不能在前面,否则子类异常 //将永远无法执行 }catch(ArithmeticException e){ }
例题:class NestedException { protected NestedException() { } public void test(String[] args) { try { int num = Integer.parseInt(args[2]); //嵌套 try/catch 块 try { int numValue = Integer.parseInt(args[0]); System.out.println(“args[0] + “的平方是 " + numValue * numValue); } catch (NumberFormatException nb) { System.out.println(“请输入数字! "); } } catch (ArrayIndexOutOfBoundsException ne) { System.out.println(“数组越界"); } }public static void main(String[] args) { NestedException obj = new NestedException(); obj.test(args); } }使用 throw 和 throws处理异常throw:Java程序在执行过程中如出现异常,会自动生成一个异常类对象,该异常对象将被提交给Java运行时系统,这个过程称为抛出(throw)异常,也可以使用throw手动抛出一个异常。throws:除了使用try/catch语句处理异常外,还可以使用throws语句直接抛出异常。 public int division(int a,int b) throws Exception{ if(b==0){ throw new Exception("除数不能为零"); }else{ return a/b; } }自定义异常使用自定义异常的时候: JavaAPI提供的内置异常不一定总能捕获程序中发生的所有错误。有时会需要创建用户自定义异常 。自定义异常需要继承Exception 或其子类class Excep{ public int division(int a,int b) throws Exception{ if(b<0){ throw new MyExcep(); //自定义异常只能手动抛出 }else{ return a/b; } }}class MyExcep extends Exception{ //自定义异常类必须继承Exception 或其子类 MyExcep(){ super("除数不能为负数!"); }}class ExcepDemo{ public static void main(String[] args){ Excep excep=new Excep(); try{ excep.division(5,-1); }catch(Exception e){ System.out.println(e.getMessage()); } }}