冲刺6

Day 6:异常处理

异常处理是确保应用程序稳定性的重要手段。以下是一个简单的Java程序

 ,可以帮助我们处理和捕获异常:
javaCopy Code
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class ExceptionHandling {
    public static void main(String[] args) {
        try {
            // 读取文件
            File file = new File("path/to/file");
            FileInputStream inputStream = new FileInputStream(file);
            byte[] buffer = new byte[1024];
            int length = inputStream.read(buffer);
            System.out.println("读取文件成功,长度为:" + length);
        } catch (FileNotFoundException e) {
            // 处理文件不存在异常
            System.out.println("文件不存在!");
        } catch (Exception e) {
            // 处理其他异常
            System.out.println("发生错误:" + e.getMessage());
        } finally {
            // 关闭文件流等资源
            System.out.println("关闭资源!");
        }
    }
}

 

posted on 2023-06-11 16:10  摸鱼队  阅读(8)  评论(0)    收藏  举报