1. Custom Exception classes:
/**@author*/Publicclass extends Exception { /*publicfileexception () { } public fileexception (String gripe) { //super (gripe); } */ Public void Printstacktrace () { System.out.println ("Suohai");} }
2. Throw an exception:
classtext{ Public Static voidT ()throwsfileexception{/** Call T (), you must catch this exception, you need to accept this exception in another class, you have to throws Exception * throws Fileexception and other class calls, you must use the Try...catch statement, whether you can Capture, * that this exception has been caught in this method, but not thrown again, the class that calls this method does not catch this exception and still Try...catch*/ /*** You can just throw an exception in a method, catch an exception when calling a method * or you can catch an exception directly within a method-that is, without the Try...catch statement, * Throw the exception directly: throw new Fileexception (" Hehe "); */ Try{ Throw NewFileexception ();//throws an exception, calling the constructor of the Fileexception class}Catch(fileexception e) {System.out.println (Oh); ThrowE//To catch the exception again outside of the method, it needs to be thrown again, because when the method is called outside, it will always be caught inside the method. } }}
3. Catching Exceptions:
Public classExceptiontest { Public Static voidMain (string[] args) {/**even if this exception is not caught, * you need to use the Try...catch statement **/ Try{text.t (); } /*catch (Fileexception e) {System.out.println ("aha"); } */ Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); } }}
4. Operation Result:
Hehe Suohai
Custom exceptions for Java learning notes