Java, create a custom exception

Abnormal Java provides system can not foresee all hope to be reporting errors, so you can define your own exception classes to represent a particular problem in the program may encounter.

If we want to define exception classes must inherit from the existing exception classes, the best choice is the exception class inherits similar meaning.

Proposed new exception type easiest way is to let the compiler generates a default constructor for you, thus reducing the amount of code written:

//编译器创建了默认的构造器,它将自动调用基类的默认构造器
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!");
		}		
	}
}

result:

 

Is defined as exception class constructor accepts a string parameter:

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);
		}
	}
}

result:

Analysis: Compared to the first, an increase in the amount of code is not large, two constructors to create a defined way MyException type of object. For the second configuration, a super keyword using an explicit call to its base class constructor, which accepts a string argument.

In an exception handler, called in printStackTrace Throwable class declaration () method. We can see from the output: it will print "from the method call until thrown at the office" method calling sequence. This information is sent to System.out, and automatically captured and displayed in the output.

 

thank you all!

Guess you like

Origin blog.csdn.net/qq_41026809/article/details/91398285