java_exception catch or throw

本文详细介绍了Java中的异常处理机制,包括异常的分类、运行时异常与普通异常的区别、异常处理的方式(try-catch-finally、throws、throw),并列举了常见的运行时异常示例。

java exception catch or throw

via: http://blog.sina.com.cn/s/blog_75698d3701012b57.html

 

1、java异常机制

java中使用Throwable对象进行异常处理,Throwable是所有异常处理的父类,有两个子类:Error和Exception

Error一般为系统异常,已知子类AnnotationFormatError, AssertionError, AWTError, CoderMalfunctionError, FactoryConfigurationError, FactoryConfigurationError, IOError, LinkageError, ServiceConfigurationError, ThreadDeath, TransformerFactoryConfigurationError, VirtualMachineError ,可以看出是非常严重错误,很难进行捕获处理,程序员很难进行修复,几乎导致程序生命周期结束,所以一般程序不进行Error异常处理。

Exception是在程序运行期间发生的不正常事件,通过异常处理机制可以使程序正常运行,这些异常是程序员能够修复处理的。

Exception又分为 运行时异常 和 普通异常

运行时异常是RuntimeException类及子类范围的异常类

除了运行异常外的Exception子类为普通异常类

 

运行异常和普通异常区别通过以下例子可以看出:

public class Tools {

 public static void fun()throws ArithmeticException,NumberFormatException{//运行时异常

  int i,j,result;

  String in="0";

  i=10;

  j=Integer.parseInt(in);

  result=i/j;

  System.out.println(result);

 }

}

public static void main(String[] args){

  Tools.fun();

}

抛出的异常为运行时异常在调用时不需要捕获异常

 

public static void fun()throws ClassNotFoundException{//普通异常

  int i,j,result;

  String in="0";

  i=10;

  j=Integer.parseInt(in);

  result=i/j;

  System.out.println(result);

}

public static void main(String[] args){

  try {

      Tools.fun();

  } catch (ClassNotFoundException e) {

     e.printStackTrace();

  }

}

抛出的异常为普通异常时,调用方法时需要异常捕获。

两者都是在运行过程中出现的异常。

 

2、java处理异常方式

java异常处理采用抓抛模式完成

抓(try{}catch(){}finally{})

try中代码可能有异常出现的代码,出现异常时终止执行异常之后代码

catch是捕获出现的异常,出现异常时执行其中代码,catch中定义捕获异常类型

finally中代码任何情况下都执行                                                                                                

Exception是异常类型的基类

public static void main(String[] args){

  try{

   int arr[]={1,0,3};

   int result=arr[0]/arr[1];

   System.out.println(result);

  }catch(Exception e){

   System.out.println("异常!");

   e.printStackTrace();//异常描述

  }finally{

   System.out.println("最终执行!");

  }

}

 

抛(throw/throws)

throws是方法抛出异常,在声明方法时定义要抛出异常类型,告知方法的调用者本方法运行过程中可能出现什么异常,在调用时应进行异常监控。(抛出的异常大多为普通异常)

public static void fun()throws ClassNotFoundException{

  int i,j,result;

  String in="0";

  i=10;

  j=Integer.parseInt(in);

  result=i/j;

  System.out.println(result);

 }

public static void main(String...args){

  try {

   Tools.fun();

  } catch (ClassNotFoundException e) {

   e.printStackTrace();

  }

 }

throw是方法内代码块抛出异常实例

class myException extends Exception{

  String msg;

  myException(int age){

  msg="age can not be positive!";

  }

  public String toString(){

  return msg;

  }

}

 

class Age{

  public void intage(int n) throws myException{

  if(n<0||n>120){

  myException e=new myException(n);

  throw e; //是一个转向语句,抛出对象实例,停止执行后面的代码

  }

  if(n>=0){

  System.out.print("合理的年龄!");

  }

}

   

public static void main(String args[]) {

  int a=-5;

  try { //try catch 必需有

  Age age = new Age();

  age.intage(a);//触发异常

  System.out.print("抛出异常后的代码") ;//这段代码是不会被执行的,程序已经被转向

  } catch (myException ex) {

  System.out.print(ex.toString());

  }

  finally{//无论抛不抛异常,无论catch语句的异常类型是否与所抛出的例外的类型一致,finally所指定的代码都要被执行,它提供了统一的出口。

  System.out.print("进入finally! ");

  }

  }

}

 

结果:年龄非法! 进入finally!

 

拓展

4.常见的运行时异常

ArithmaticExceptionDemo.java

public class ArithmaticExceptionDemo {   

    //计算两个数相除的结果   

    public int divide(int a,int b){

            return a/b;

    }

    

    //抛出异常

    //Exception in thread "main" java.lang.ArithmeticException: / by zero   

    public static void main(String args[]){

            ArithmaticExceptionDemo excp = new ArithmaticExceptionDemo();

            excp.divide(10,0);

    }   

}

 

ArrayStoreExceptionDemo.java

public class ArrayStoreExceptionDemo {

    //程序的入口

    public static void main(String arsg[]){

            //Object类型 字符串数组

            Object x[] = new String[3];

            

            //为了不让程序在编译时就检查报错 就故意写成上述类型

            //如果写成 下面类型就会直接报错

            //String x [] = new String[3];

            

            try{

                //错误的类型 java.lang.ArrayStoreException: java.lang.Integer

                 x[0] = new Integer(0);

            }catch(ArrayStoreException ae){

                    System.err.println(ae.toString()+"ok");

                    ae.printStackTrace();

            }

            System.out.println("程序正常运行!");

    }

}

 

ClassCastExceptionDemo.java  

public class ClassCastExceptionDemo {   

       

    public static void main(String args[]){   

               

            Object x = new Integer(12);   

           

            try{   

                System.out.println((String)x);   

            }catch(ClassCastException ce){   

                    System.err.println(ce.toString());   

                }   

    }   

  

}  

 

 

EmptyStackExceptionDemo.java

import java.util.EmptyStackException;

import java.util.Stack;

public class EmptyStackExceptionDemo {

    public static void main(String args[]){

        Stack<String> s = new Stack<String>(); //栈

        s.push("a");    //先压入 a      压栈 push()方法

        s.push("b");    //    b 

        s.push("c");    // 最后压入 c   

        

        try{

            while(s.size()>0){

                System.out.println( s.pop());    //依次循环将栈中的元素弹出 pop()方法

            }

            s.pop(); // 此动作将造成异常,因为栈中所有元素在上面的 循环中就已经弹出,为空栈

        }catch(EmptyStackException ee){

                System.err.println(ee.toString());

                ee.printStackTrace();

            }

    }

}

 

 

IndexOutOfBoundsExceptionDemo.java

public class IndexOutOfBoundsExceptionDemo {

    public static void main(String args[]){

            int num [] = new int[10];

            try{

                //数组10个长度   12次循环就报错

                for(int i=0;i<12;i++){

                    System.out.println(num[i]); //循环超出范围

                }

            }catch(IndexOutOfBoundsException ie){

                    System.err.println(ie.toString());

                    ie.printStackTrace();

                    System.out.println( ie.getCause());

                    System.err.println(ie.getMessage());

                }   

            System.out.println("程序还 能继续执行");

        }

}

 

 

NegativeArraySizeExceptionDemo.java

public class NegativeArraySizeExceptionDemo {

    public static void main(String args[]){

            try{

                int num [] = new int [-9];   //创建大小为负的数组,则抛出该异常

                System.out.println(num[0]);

            }catch(NegativeArraySizeException ne){

                System.err.println(ne.toString()); //err红色打印

                ne.printStackTrace();

            }

        }

}

 

 

NullPointerExceptionDemo.java

public class NullPointerExceptionDemo {

    String nameString;  //类字符串成员变量  默认为null

    public static void main(String args[]){

            try{

                //返回字符串第一个字符 但将出现异常 相当于 null.charAt(0);

                char c = new NullPointerExceptionDemo().nameString.charAt(0);

                System.out.println(c);

            }catch(NullPointerException ne){

                System.err.println(ne.toString());

                ne.printStackTrace();

            }

        }

}

 

 

NumberFormatExceptionDemo.java

public class NumberFormatExceptionDemo {

    public static void main(String args[]){

            String a = "3";

            int b = (int)new Integer(a);

            System.out.println(b);//这个是没有问题的

            try{

                String c = "aa";

                //java.lang.NumberFormatException: For input string: "aa"

                int d = (int)new Integer(c);

                System.out.println(d);//这个是有问题的

            }catch(NumberFormatException ne){

                System.err.println(ne.toString());

                ne.printStackTrace();

            }

        }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值