java异常

来源:互联网 发布:国家大力发展人工智能 编辑:程序博客网 时间:2024/06/10 01:12

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语句抛出新的异常