可以一个try对应多个catch。下边的例子a/b,b可能为0,报ArithmeticException;div(int a,int b)中,int[] arr=new int[a]; System.out.println(arr[3]); a如果小于3,就报ArrayIndexOutOfBoundsException。代码如下。
- class Demo
- {
- int div(int a,int b)throws ArithmeticException,ArrayIndexOutOfBoundsException
- {
- int[] arr=new int[a];
- System.out.println(arr[3]);
- return a/b;
- }
- }
- class ExceptionDemo
- {
- public static void main(String[] args) //throws Exception
- {
- Demo d=new Demo();
- try
- {
- int res=d.div(3,2);
- System.out.println(res);
-
- }
- catch (ArithmeticException e)
- {
- e.printStackTrace();
-
- }
- catch(ArrayIndexOutOfBoundsException e)
- {
- //System.exit(0);
- System.out.println("角标越界");
-
- }
- catch(Exception e)
- {
- e.printStackTrace();
- }
- finally
- {
- System.out.println("finally");
- }
-
-
- System.out.println("over");
- }
- }
复制代码 |