Java之创建自定义异常

Java提供的异常体系不可能预见所有的希望加以报告的错误,所以可以自己定义异常类来表示程序中可能会遇到的特定问题。

如果我们要定义异常类,必须从已有的异常类继承,最好是选择意思相近的异常类继承。

建议新的异常类型最简便的方法就是让编译器为你产生默认构造器,这样就减少了写入代码的量:

//编译器创建了默认的构造器,它将自动调用基类的默认构造器
class SimpleException extends Exception{}

public class InheritingExceptions {
	public void f() throws SimpleException{
		System.out.println("Throw SimpleException from f()");
		throw new SimpleException();
	}
	public static void main(String[] args) {
		InheritingExceptions sed = new InheritingExceptions();
		try {
			sed.f();
		}catch(SimpleException e) {
			System.out.println("Caught it!");
		}		
	}
}

结果:

为异常类定义一个接受字符串参数的构造器:

class MyException extends Exception{
	public MyException() {}
	public MyException(String msg) {
		super(msg);
	}
}
public class FullConstructors {
	public static void f() throws MyException{
		System.out.println("Throwing MyException from f()");
		throw new MyException();
	}
	public static void g() throws MyException{
		System.out.println("Throwing MyException from g()");
		throw new MyException("Originated in g()");
	}
	public static void main(String[] args) {
		try {
			f();
		}catch(MyException e) {
			e.printStackTrace(System.out);
		}try{
			g();
		}
		catch(MyException e) {
			e.printStackTrace(System.out);
		}
	}
}

结果:

分析:相比第一个而言,增加的代码量并不大,两个构造器定义了MyException类型对象的创建方式。对于第二个构造器而言,使用super关键字明确调用了其基类构造器,它接受一个字符串作为参数。

在异常处理程序中,调用了在Throwable类声明的printStackTrace()方法。从输出可以看到:它将打印“从方法调用处直到抛出异常处”的方法调用序列。这里信息被发送到了System.out,并且自动地被捕获和显示在输出中。

谢谢大家!

猜你喜欢

转载自blog.csdn.net/qq_41026809/article/details/91398285