Java niu Jiao Jian "007": Error in Java can be catch
There are many friends on the internet who say that error in Java cannot be caught, and that the type of error defined in Java is difficult to test, so be sure to do so.
But maybe everyone has noticed that we often see code like this
[Java]View PlainCopy
- try{
- ...
- }catch (Throwable ex) {
- ...
- }
Where catch is directly captured is a Throwable class, open the inheritance relationship to see, exception and error two classes are also inherited from the Throwable class, then, that is, error should be able to be captured, here is an example to prove the guess:
[Java]View PlainCopy
- Package net.moon.demo.errorcatch;
- Public class Demo {
- /**
- * @param args
- */
- public static void Main (string[] args) {
- //TODO auto-generated method stub
- try {
- throw New Myerror ("My Error");
- } catch (Myerror e) {
- System.out.println (E.getmessage ());
- }
- }
- }
- Class Myerror extends Error {
- /**
- *
- */
- private Static final long serialversionuid = 1L;
- Public Myerror () {
- super ();
- //TODO auto-generated constructor stub
- }
- Public myerror (String message, throwable cause) {
- super (message, cause);
- //TODO auto-generated constructor stub
- }
- Public myerror (String message) {
- super (message);
- //TODO auto-generated constructor stub
- }
- Public Myerror (Throwable cause) {
- super (cause);
- //TODO auto-generated constructor stub
- }
- }
Execute the above code, as the previous guess, error is can be captured, run the code result is:
[XHTML]View PlainCopy
- My Error
Here is a small example to verify the capture of the error.
Copy CodeThe code is as follows:
public class Testcatcherror extends error{
Private static final long serialversionuid = -351488225420878020l;
Public Testcatcherror () {
Super ();
}
Public Testcatcherror (String msg) {
Super (MSG);
}
public static void Main (string[] args) {
try {
throw new Testcatcherror ("Test catch Error");
} catch (Throwable t) {
SYSTEM.OUT.PRINTLN ("step in the Catch ~");
T.printstacktrace ();
}
}
}
Operation Result:
Copy CodeThe code is as follows:
Step in the Catch ~
Testcatcherror:test Catch Error
At Testcatcherror.main (testcatcherror.java:23)
Java niu Jiao Jian "007": Error in Java can be catch