I have seen many friends on the Internet saying that errors in Java cannot be caught, and the error type defined in Java is hard to be tested. I think so.
But you may be aware that we often see such code
Try {<br/>... <br/>} catch (throwable ex) {<br/>... <br/>}
The catch directly captures a throwable class. Open the inheritance relationship and you can see that the exception and error classes are also inherited from the throwable class, that is to say, the error should be captured. The following is an example to prove your guess:
Package net. moon. demo. errorcatch; </P> <p> public class demo {</P> <p>/** <br/> * @ Param ARGs <br/> */<br/> Public static void main (string [] ARGs) {<br/> // todo auto-generated method stub <br/> try {<br/> throw new myerror ("My error "); <br/>} catch (myerror e) {<br/> system. out. println (E. getmessage ()); <br/>}</P> <p> class myerror extends error {</P> <p> /** <br/> */<br/> Private Static final long serialversionuid = 1l; </P> <p> Public myerror () {<br/> super (); <br/> // todo auto-generated constructor stub <br/>}</P> <p> Public myerror (string message, throwable cause) {<br/> super (message, cause ); <br/> // todo auto-generated constructor stub <br/>}</P> <p> Public myerror (string message) {<br/> super (Message ); <br/> // todo auto-generated constructor stub <br/>}</P> <p> Public myerror (throwable cause) {<br/> super (cause ); <br/> // todo auto-generated constructor stub <br/>}</P> <p >}< br/>
Execute the above Code, which can be captured like an error, and the result of running the code is:
My error <br/>
Next article: Java tip [008]: Can I start a thread by calling the run method of a thread?