[java] java异常

1.java异常是用来做什么的

java使用异常来提供一致的错误报告模型

2.创建异常类
//所有自定义的异常类都必须继承已存在的异常类
public class Myexception extends Exception{

    public Myexception() {
    }

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

}
public class exceptionTest {
    public void f() throws Myexception {
        throw new Myexception();
    }
    public void g() throws Myexception {
        throw new Myexception("这是g异常");
    }
    @Test
    public void test1() {
        try {
            FileOutputStream fileOutputStream = new FileOutputStream("H:\\javaio\\error.txt");
            PrintStream printStream = new PrintStream(fileOutputStream);

//printWriter无法将信息打印到文件中??
            FileWriter fileWriter = new FileWriter("H:\\javaio\\error2.txt");
            PrintWriter printWriter = new PrintWriter(fileWriter);

            try {
                f();
            } catch (Myexception e) {
                e.printStackTrace(printStream);
            }

            try {
                g();
            } catch (Myexception e) {
                e.printStackTrace(printWriter);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
3.异常类的printStackTrace()方法
//此方法有四个重载
	public void printStackTrace() {
        printStackTrace(System.err);
    }
	public void printStackTrace(PrintStream s) {
        printStackTrace(new WrappedPrintStream(s));
    }
	public void printStackTrace(PrintWriter s) {
        printStackTrace(new WrappedPrintWriter(s));
    }
//默认通过标准出错流打印到控制台,也可以通过标准输出System.out打印到控制台
//可以传入PrintStream对象或者其子类对象  PrintStream-->FilterOutputStream-->OutputStream
//可以传入PrintWriter对象或其子类对象   PrintWriter-->Writer
4.异常链

通常需要在处理一个异常后在抛出另一个异常,需要在catch块中再执行throw语句抛出新的异常

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值