Java异常机制---异常处理方法

1. Try Catch,捕获并处理

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

/**
 * 测试异常处理方法,引用I/O,读取文件
 * @author Administrator
 *
 */
public class TestException02 {
	public static void main(String[] args) {
		//变量声明放在try方法外,可以在多个方法内使用
		FileReader reader = null;
		try {
			 reader =  new FileReader("E:/new folder/a.txt");
			char c = (char)reader.read();
			char c2 = (char)reader.read();
			char c3 = (char)reader.read();
			System.out.println(""+c+c2+c3);
		}
		//捕获异常时,如果异常之间存在继承关系,需要把子类放在父类前面
		catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (IOException e){
			e.printStackTrace();
		}finally{
			try {
				if (reader!= null) {
					reader.close();
				}
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

2. 抛给上级处理 throws

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

/**
 * 测试异常处理方法,throws 在方法名后面声明异常,抛给上一级处理,调用方法时处理,
 * 可以声明多个异常
 * 抛出异常时,子类抛出的异常不能超过父类异常的范围
 * 父类没有声明异常,子类也不能声明
 * 使用throw可以手动抛出异常
 * @author Administrator
 *
 */
public class TestException04 {
	public static void main(String[] args) {
		String str = "";
		try {
			str = new TestException04().openFile();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(str);
	}
	
	String openFile() throws FileNotFoundException,IOException{
		
			FileInputStream fis = new FileInputStream("E:/new folder/a.txt");
			
			char c = (char) fis.read();
			return c+"";
}
}

3. 自定义异常抛出

/**
 * 自定义异常 从Exception或其子类中派生一个类,作为自定义的异常类
 * 重写其构造器
 * 
 * @author Administrator
 *
 */
public class TestExcepyion05 {
	public static void main(String[] args) {
		MyException me = new MyException();
		try {
			me.test();
		} catch (MyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

class MyException extends Exception {
	public MyException() {

	}

	public MyException(String message) {
		super(message);
	}

	void test() throws MyException {

	}
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值