常见的运行时异常(RuntimeException) 和复制中的异常处理

空指针异常: NullPointerException

数组下标越界异常:ArrayIndexOutOfBoundsException

字符串下标越界异常:StringIndexOutOfBoundsException

不合法的参数异常:IllegalArgumentException

算术异常:ArithmeticException

数字格式化异常:NumberFormatException

类造型异常:ClassCastException

复制中自定义异常的处理:

代码如下:

自定义一个异常类,其继承了Excetion类

 

public class CopyException extends Exception{

	public CopyException() {
		super();
	}

	public CopyException(String message, Throwable cause) {
		super(message, cause);
	}

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

	public CopyException(Throwable cause) {
		super(cause);
	}
	
}

测试类 代码如下:

 

 

public class TestDemo5 {
	public static void main(String[] args) throws CopyException {
		FileInputStream fis = null;
		FileOutputStream fos = null;
		System.out.println("开始");
		try {
			fis = new FileInputStream("pw.txt");
			fos = new FileOutputStream("copy.txt");
			int d = -1;
			while( (d = fis.read())!=-1 ){
			fos.write(d);
			}
			System.out.println("复制完毕");
		} catch (FileNotFoundException e) {
			//抛出自定义异常
			throw new CopyException("文件没有找到",e);
		} catch (IOException e) {
			//抛出自定义异常
			throw new CopyException("读写异常",e);
		} finally {
			if(fis != null){
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(fos != null){
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

 

 

 

 

 

 

 

 

你可能感兴趣的:(java基础,文件操作(有异常处理))