天天看點

異常處理機制:兩種方式

throws + 異常類型

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

/**
 * @author xianyu
 * @version 1.0
 * @date 2020/1/1 15:53
 */
public class ExceptionTest2 {

    public static void main(String[] args){

        // 可以在最終調用時處理
        try {
            method2();
        } catch (IOException e) {
            e.printStackTrace();
        }

        method3();
    }


    // method3進行了異常處理
    public static void method3(){
        try {
            method2();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 這裡任然向上抛出異常
    public static void method2() throws IOException{
        method1();
    }

    // 異常跑出去,給調用該方法的方法去處理
    public static void method1() throws FileNotFoundException,IOException {
        File file = new File("hello1.txt");
        FileInputStream fis = new FileInputStream(file);

        int data = fis.read();
        while(data != -1){
            System.out.print((char)data);
            data = fis.read();
        }

        fis.close();


    }



}



           

try – catch – finally

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

/**
 * @author xianyu
 * @version 1.0
 * @date 2020/1/1 15:35
 */
public class ExcceptionTest {

    public static void main(String[] args) {
        // 異常測試
        String str = "123";
        //str = "abc";
        int num = 0;
        try{
            num = Integer.parseInt(str);
        }catch (NumberFormatException e){
            //System.out.println("出現數值轉換異常了");
            e.printStackTrace();
        }
        System.out.println(num);
        System.out.println("***************************");

        File file = new File("hello.txt");
        try {
            FileInputStream fis = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }


    }
}