异常处理机制:两种方式

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();
        }


    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值