IO流_try...catch的方式处理异常1

101 篇文章 0 订阅
15 篇文章 0 订阅
package cn.itcast_02;

/*
 * 我们自已如何处理异常呢?
 * 		A:try...catch...finally
 * 		B:throws	抛出
 * 
 * try...catch...finally的处理格式:
 * 		try{
 * 			可能出理问题的代码;
 * 		}catch(异常名	变量){
 * 			针对问题的处理	
 * 		}finally{
 * 			释放资源;
 * 		}
 * 
 * 变形格式:
 * 		try{
 * 			可能出现问题的代码
 * 		}catch(异常名	变量){
 * 			针对问题的处理
 * 		}
 * 
 * 注意:
 * 		A:try里面的代码越少越好。
 * 		B:cathc里面必须有内容,那怕是给出一个简单的提示。
 */
public class ExceptionDemo {
	public static void main(String[] args) {
		int a = 10;
		int b = 0;
		// System.out.println(a / b);
		try {
			System.out.println(a / b);
		} catch (ArithmeticException ae) {
			System.out.println("除数不能为零");
		}
		System.out.println("over");
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是exp5_2.java的代码实现: ```java import java.io.*; public class exp5_2 { public static void main(String[] args) { // 读取exp5_1.txt中的内容 try { FileInputStream fileInputStream = new FileInputStream("exp5_1.txt"); FileOutputStream fileOutputStream = new FileOutputStream("exp5_3.txt"); int b; while ((b = fileInputStream.read()) != -1) { if (b % 2 == 1) { fileOutputStream.write(b); fileOutputStream.write(' '); } } fileInputStream.close(); fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } // 读取exp5_2.txt中的内容 try { FileReader fileReader = new FileReader("exp5_2.txt"); FileWriter fileWriter = new FileWriter("exp5_4.txt"); int c; while ((c = fileReader.read()) != -1) { if (c % 2 == 0) { fileWriter.write(c); fileWriter.write(' '); } } fileReader.close(); fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` 程序使用字节方式读出文件exp5_1.txt中的内容,然后将文件中的所有奇数写入文件ex5_3.txt中;使用字符方式读出文件exp5_2.txt中的内容,然后将文件中的所有偶数写入文件exp5_4.txt中。 程序中使用了FileInputStream和FileOutputStream来读写文件,并使用FileReader和FileWriter来读写文本文件。在读取文件时,程序使用了while循环,并用read()方法读取文件的每个字节或字符,直到读到文件结尾为止。 请注意,这里程序并没有关闭文件,实际应用中应该使用try-with-resources或手动关闭文件来避免资源泄漏。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值