Java-10.3 custom exception types
In this section, we will briefly discuss the custom exception types.
Generally, the exception types defined in java are enough for us to use. However, we need other custom types in actual operations.
In the exception section, the class name is generally enough.
The following is the simplest custom exception type:
package com.ray.ch10;public class Test {public static void main(String[] args) throws SimpleException {throw new SimpleException();}}class SimpleException extends Exception {}
In the development process, the above Code is too simple and useless. let's expand it:
Package com. ray. ch10; public class Test {public static void main (String [] args) throws SimpleException {// throw new SimpleException (); throw new SimpleException (custom exception );}} class SimpleException extends Exception {public SimpleException () {} public SimpleException (String msg) {super (msg );}}
Output:
Com. ray. ch10.SimpleException: custom exception
At com. ray. ch10.Test. main (Test. java: 7)
We add custom information to the code. In this way, the basic requirements can be met.
The above code inputs the output stream into the standard error stream. However, we can use the following modifications to process the output part as a normal output stream.
Package com. ray. ch10; public class Test {public static void main (String [] args) {// throw new SimpleException (); try {throw new SimpleException (custom exception );} catch (SimpleException e) {e. printStackTrace (System. out); // changed place }}} class SimpleException extends Exception {public SimpleException () {} public SimpleException (String msg) {super (msg );}}
Output:
Com. ray. ch10.SimpleException: custom exception
At com. ray. ch10.Test. main (Test. java: 7)
The two outputs are the same, but if we put the code in the ide, the output will be different.