在java中的Try Catch块-------------异常处理(2)

1. Try块是什么?

Try块是一块可能产生异常的代码块,一个Try块可能跟着Catch块或者Finally块,或者两者。

Try块的语义:

try{
   //statements that may cause an exception
}

2. Catch块是什么?

一个Catch块关联一个Try块,如果在Try块中有一个特定类型的异常发生,则响应的Catch块会执行,例如,

如果在Try块中arithmmetic exception发生,那么对应arithmmetic exception的Catch块会发生。

Catch块的语义:

try
{
     //statements that may cause an exception
}
catch (exception(type) e(object))‏
{
     //error handling code
}

3. Try-Catch块的执行流程

如果在try块中的异常发生,则执行的控制将会被传到Catch块中,异常被相应的Catch块所捕获,一个

Try块可以有多个Catch块,但是每一个Catch块仅仅能定义一种异常类,

当Try块中的所有代码执行完之后,在Finally块中的代码将会执行。包含一个Finally块并不是强制的,

但是如果你有Finally块,它将会运行,不管有没有异常剖出或者处理。

 

一个Try-Catch的例子:

class Example1 {
   public static void main(String args[]) {
     int num1, num2;
     try { 
        // Try block to handle code that may cause exception
        num1 = 0;
        num2 = 62 / num1;
        System.out.println("Try block message");
     } catch (ArithmeticException e) { 
            // This block is to catch divide-by-zero error
            System.out.println("Error: Don't divide a number by zero");
       }
     System.out.println("I'm out of try-catch block in Java.");
   }
}

输出:

Error: Don't divide a number by zero
I'm out of try-catch block in Java.

4. 在java中的多个代码块

一个Try块可以有多个Catch块

一个捕获Exception类的Catch块可以捕获其他的异常

catch(Exception e){
  //This catch block catches all the exceptions
}

如果有多个Catch块存在,则上面提到的Catch应该放到最后。

如果Try块没有抛出异常,则Catch块将被忽略,程序将会继续。

如果Try块抛出异常,则相应的Catch块将会处理它。

在Catch块中的代码将会执行,然后程序继续执行。

class Example2{
   public static void main(String args[]){
     try{
         int a[]=new int[7];
         a[4]=30/0;
         System.out.println("First print statement in try block");
     }
     catch(ArithmeticException e){
        System.out.println("Warning: ArithmeticException");
     }
     catch(ArrayIndexOutOfBoundsException e){
        System.out.println("Warning: ArrayIndexOutOfBoundsException");
     }
     catch(Exception e){
        System.out.println("Warning: Some Other exception");
     }
   System.out.println("Out of try-catch block...");
  }
}
输出:
Warning: ArithmeticException
Out of try-catch block...


posted @ 2015-12-01 11:25  峰峰仔  阅读(634)  评论(0编辑  收藏  举报