天天看點

3 使用try-catch捕捉異常

處理異常

可以使用try…catch…處理異常,例如之前的程式可以使用try…catch…處理

package com.monkey1024.exception;

import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class ExceptionTest02 {

    public static void main(String[] args) {
         try {
            FileInputStream fis = new FileInputStream("d:/monkey1024.txt");
            //捕捉FileNotFoundException異常
        } catch (FileNotFoundException e) {//jvm會建立FileNotFoundException的對象,然後将e指向這個對象
            //如果try裡面的代碼沒有報錯,則不會執行catch裡面的代碼
            e.printStackTrace();//列印出異常資訊
            String msg = e.getMessage();
            System.out.println(msg);
        }
        System.out.println("monkey1024.com");//catch後面的語句會正常執行
    }

}

           

可以捕捉多個異常,但是catch裡面必須從小類型異常到大類型異常進行捕捉,先捕捉子後捕捉父,最多執行一個catch語句塊裡面的内容。

package com.monkey1024.exception;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class ExceptionTest02 {

    public static void main(String[] args) {
         try {
            FileInputStream fis = new FileInputStream("d:/monkey1024.txt");
            fis.read();
        } catch (FileNotFoundException e) {//捕捉FileNotFoundException異常
            e.printStackTrace();
        } catch (IOException e) {//捕捉IOException異常
            e.printStackTrace();
        } catch (Exception e) {//捕捉Exception異常
            e.printStackTrace();
        } 
    }

}
           

jdk7新特性

jdk7新特性,可以将多個捕捉的異常放到一個catch裡面

ackage com.monkey1024.exception;

import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class ExceptionTest03 {

    public static void main(String[] args) {

        try {
            System.out.println(1024 / 0);
            FileInputStream fis = new FileInputStream("d:/monkey1024.txt");
            //jdk7新特性,可以将多個異常放到一個catch裡面
        } catch (FileNotFoundException | ArithmeticException e) {
            e.printStackTrace();
        } /*catch (ArithmeticException e){
            e.printStackTrace();
        }*/
    }

}
           

繼續閱讀