Java Exception capture

Source: Internet
Author: User

class ExampleA inherit exception, class Exampleb inherit ExampleA.
The following code fragment is available:

Try {    thrownew Exampleb ("B"catch(ExampleA e) {    System.out.println ("ExampleA"catch(Exception e) {    System.out.println ( "Exception");}

what is the output of executing this piece of code?

According to the principle of substitution of the Richter scale [a subtype can be used where the parent type is used], the catch block that grabs the ExampleA type exception catches the exception of the Exampleb type thrown in the try block, so the output: ExampleA.

So what is the result of running the code below? (The source of the problem is "Java Programming ideas" book)

Class Annoyance extends Exception {}class Sneeze extends annoyance {}class Human {public    static void Main (string[] Ar GS)         throws Exception {        try {            try {                throw new sneeze ();            }             catch (Annoyance a) {                System.out.println ("caught annoyance");                throw A;            }        }         catch (Sneeze s) {            System.out.println ("Caught Sneeze");            return;        }        finally {            System.out.println ("Hello world!");}}}    

The answer is:

Caught annoyance  caught sneeze  Hello World

The first row and the third row have no doubt, the key is the second line, should come out? Does the subclass catch the exception of the parent class?

Although

Catch (Annoyance a)

This sentence uses a reference to the parent class, but is actually the object of the subclass, which is the classic representation of polymorphism in Java. In

Catch

Of course you can catch the exception that you throw out.

Java Exception capture

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.