TheStar

导航

 

 

package com.direct.work;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;


public class ExceptionDemo {

	public static void main(String[] args) {
		int num = 10;
		int num2 = 0;
		int temp;
		try {
			temp = num/num2;//运算不正常异常
		} catch (ArithmeticException e) {	
			PrintStream ps	= null;
			try {
				ps = new PrintStream("e:\\errorInfo.txt");//流创建此文件
			} catch (FileNotFoundException e1) {
				e1.printStackTrace();
			} 
			//e.printStackTrace(ps);//打印异常到文件中
			//e.printStackTrace();//打印到控制台
			try {
				ps.write(e.toString().getBytes());//异常信息转换为字节数组,写入文件中
			} catch (IOException e1) {
				e1.printStackTrace();
			}
	
		}
		//自定义异常测试
		MException me = new MException();
		try {
			me.division(10, 0);
		} catch (MyException e) {
			e.printStackTrace();
		}
		
		
	}
}
class MyException extends Exception{
	public MyException(String message){
		super(message);//打印信息,父类的方法
	}
}
class MException{
	public void division(int num1,int num2)throws MyException{
		if (num2<0) {
			throw new MyException("除数不能为负数");
		}
		if(num2 ==0){
			throw new MyException("除数不能为0");
		}
	}
}

  

 

posted on 2017-12-14 16:27  TheStar  阅读(693)  评论(0编辑  收藏  举报