class="hide-preCode-box">

在这里插入图片描述

5、编译型异常案例

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.InputMismatchException;
import java.util.Scanner;

/**
 * package:PACKAGE_NAME
 *
 * @Author jimmy-yan
 * @Create 2024/11/18 17:14
 */
public class ExceptionTest {

    public static void main(String[] args) {
        ExceptionTest e = new ExceptionTest();
//        e.test();
//        e.test1();
        e.test2();
    }

    public void test() {
        try {
            Scanner scanner = new Scanner(System.in);
            int num = scanner.nextInt();
            System.out.println(num);
        } catch (InputMismatchException e) {
            System.out.println("出现了InputMismatchException异常");
        } catch (RuntimeException e) {
            System.out.println("出现了RuntimeException异常");
        }
        System.out.println("异常处理结束,代码继续执行");

    }

    public void test1() {
        try {
            String str = "123";
            str = "abc";
            int i = Integer.parseInt(str);
            System.out.println(i);

        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        System.out.println("程序执行结束");
    }

    public void test2() {
        try {
            File file = new File("D:\\hello.txt");
            FileInputStream fis = new FileInputStream(file);  //可能报FileFonudException

            int data = fis.read(); //可能报IOException
            while (data != -1) {
                System.out.println((char) data);
                data = fis.read(); //可能报IOException
            }
            fis.close();  //可能报IOException
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
 class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}"> class="hide-preCode-box">

6、开发体会

对于运行时异常:

开发中,通常就不进行显示的处理了,一旦在程序执行中,出现了运行时异常,那么就根据异常的提示信息修改代码即可。

对于编译型异常:

一定要处理,否则代码不能执行通过

data-report-view="{"mod":"1585297308_001","spm":"1001.2101.3001.6548","dest":"https://blog.csdn.net/YZL40514131/article/details/143859200","extend1":"pc","ab":"new"}">>
注:本文转载自blog.csdn.net的敲代码敲到头发茂密的文章"https://blog.csdn.net/YZL40514131/article/details/143859200"。版权归原作者所有,此博客不拥有其著作权,亦不承担相应法律责任。如有侵权,请联系我们删除。
复制链接

评论记录:

未查询到任何数据!