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 {

	}
}

猜你喜欢

转载自blog.csdn.net/qq_30007589/article/details/80851221