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