java異常處理的使用 – JAVA編程語言程序開發技術文章

package com.robert.test1; 
 
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.IOException; 
import java.io.InputStream; 
 
/** 
 * @author Administrator 
 *測試try catch塊的執行路徑 
 */ 
public class TryCatchTest { 
 
    public static void main(String[] args) { 
         
        try  
        { 
            InputStream inputStream = new FileInputStream("abc"); 
            inputStream.read(); 
        }  
        catch (FileNotFoundException e)  
        { 
            System.out.println("throw a FileNotFoundException"); 
        }  
        catch (IOException e)  
        { 
            System.out.println("throw a IOException!"); 
        } 
        System.out.println("hello world!"); 
    } 

 
 
當文件找不到時: 
輸出:

throw a FileNotFoundException
hello world!

 
package com.robert.test1; 
 
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.IOException; 
import java.io.InputStream; 
 
/** 
 * @author Administrator 
 *測試try catch塊的執行路徑 
 */ 
public class TryCatchTest { 
 
    public static void main(String[] args) { 
         
        try { 
            InputStream inputStream = new FileInputStream("abc"); 
            inputStream.read(); 
        } catch (FileNotFoundException e) { 
            System.out.println("throw a FileNotFoundException"); 
            return; 
        } catch (IOException e) { 
            System.out.println("throw a IOException!"); 
            return; 
        } 
        System.out.println("hello world!"); 
    } 
}  www.aiwalls.com

在catch塊中加入return ,當程序遇到異常(FileNotFoundException,IOException)的時候會被返回。即catch後的代碼不會被執行。

輸出:

throw a FileNotFoundException
 

package com.robert.test1; 
 
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.IOException; 
import java.io.InputStream; 
 
/** 
 * @author Administrator 
 *測試try catch塊的執行路徑 
 */ 
public class TryCatchTest { 
 
    public static void main(String[] args) { 
         
        try  
        { 
            InputStream inputStream = new FileInputStream("abc"); 
            inputStream.read(); 
        }  
        catch (FileNotFoundException e)  
        { 
            System.out.println("throw a FileNotFoundException"); 
            return; 
        }  
        catch (IOException e)  
        { 
            System.out.println("throw a IOException!"); 
            return; 
        } 
        finally 
        { 
            System.out.println("finally"); 
        } 
        System.out.println("hello world!"); 
    } 

如果後finally,程序遇到異常(FileNotFoundException,IOException) ,finally塊中的代碼也會被執行到。

輸出:

throw a FileNotFoundException
finally

摘自 zbwork000的專欄
 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *