Java tip [007]: Can errors in Java be caught?

Source: Internet
Author: User

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?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.