Exception in super and sub class

when super class method throws an exception then sub class overridden method can throws child exception but when we talk about constructor why we throws parent class exception in derived class constructor????

tcbhardwaj wrote:
     C() throws Throwable // why here parent of Exception class
     void ok() throws ArithmeticException // why here child of RunTimeException classFirst, you never need to declare a throws clause for unchecked exceptions--RuntimeException, Error, and their descendants.
However, there are a couple of general rules for checked exceptions (such as IOException, SQLException, etc.). As you're studying these, keep in mind that a throws clause is a contract that promises what the method will not do. In particular, it doesn't promise that the method will throw those exceptions. It promises that it will not throw any other checked exceptions not covered by that throws clause.
1. A child method that overrides a parent method cannot throw any checked exception outside what's covered by the parent's throws clause. So if the parent method declared throws IOException, the child cannot declare throws Exception, or throws SQLException, because both of those are outside the IOException "sub-hierarchy."
2. A child method that overrides a parent method can declare to throw less than the parent throws. This is because, if the parent promises not to throw outside of some set, and the child promises not throw outside of a subset of that set, then clearly he's also not throwing outside of the parent's set. If the parent method declares throws SQLException, IOException, then the child can declare no exceptions at all, or just SQLException, or just IOException, or any combination of any of the subclasses of SQLE and IOE.
Rules 1 and 2 do not apply in the case of constructors, because no constructor can ever override another constructor.
3. When any method or constructor, A, invokes any other method or constructor, B, then any checked exception declared to be thrown by B must be either caught or declared to be thrown by A. If A catches or throws a parent of an exception thrown by B, then he's also implicitly catching or throwing the one that B mentions.

Similar Messages

  • Super and sub classes

    Using an Super class and couple of subclasses of this super.
    Super{
    m1(){
    subclass1, subclass2, subclass3...etc.
    these subclasses call super class method m1().
    In super class m1() want to know which subclass called this method m1(). how to find this?
    Ofcourse can use a variable and in super and set it in subclass but is there a smart way in java to find this. I would appreciate your help.
    Thanks.

    if (this instanceof SuperClass)
    if (this instanceof SubClass1)
    etc.
    But this is very poor design. You should override m1() in each subclass to have it do whatever is necessary in each case.

  • Question about throws exception in interface and realized class

    Hi,all
    If I define a method In the interface like that-
    public void Execute() throws NumberFormatException; In the realized class, I can define this method like that-
    public void Execute() throws RuntimeException{
            System.out.println("test");       
    }This is a right realization. But if I manage it to throws Exception or to throws Throwable in the class it leads a error. Why add this restrict only to Exception? What is the purpose of this way?
    Greetings and thanks,
    Jason

    When you say "throws NumberFormatException" you are really saying:
    When using classes implementing this interface, you have to be prepared to deal with them throwing a NumberFormatException. Other exceptions won't happen.
    When you come to implement it, it might not be possible for it to throw a NumberFormatException, so there's no reason why you should have to lie about that. Code handling it directly will be fine (it doesn't throw a NFE) and code handling it via the interface will be fine (it will handle NFEs, they just don't happen).
    If your concrete implementation throws other sorts of exception, such as Exception or IOException, and so on, it's incompatible with code that's manipulating the interface. The interface says "NFEs might get thrown, nothing else will." while your implementation says "IOExceptions might get thrown".
    So that explains why you can't use arbitrary exceptions. The special case is RuntimeException. RuntimeExceptions don't have to be caught, and it's expected that they can happen at any time - so there's no point trying to catch and handle them as a general case.
    The classic example of a RuntimeException is a NullPointerException. You don't need to declare your method as throwing a NullPointerException even though it might get thrown. And you don't have to add NullPointerException to the throws part of the interface definition, because you already know that the concrete implementation could throw a NPE at any time.
    Hope that helps (a little).
    I'd recommend reading the API documentation on RuntimeException and Exception to get a clearer insight into this.
    Dave.

  • Super and Sub Types

    Hi All.
    I have 2 tables:- Worker and LeadProfessional.
    Worker is the super type for LeadProfessional and they display as box in box in both the logical and relational views. However, when I generate the DDL it creates a separate table for LeadProfessional which I did not expect or want. How can I get it to include LeadProfessional inside Worker in the DDL?

    Hi,
    You should be able to do this by opening the property dialog for Entity Worker (in the Logical Model), selecting its Subtypes panel and setting the Subtree generation field to Single Table.
    Then do an Engineer to Relational Model and generate your DDL.
    David

  • Extending and sub classing

    i'm experimenting with extending and subclassing components in flex. i am trying to add an event listener to the datagridcolumn. i want to add a function to occur when i click the column (using a mouseclickevent).
    each of my pieces of data in the datagrid have a custom style to look like a hyperlink (blue and underlined). the user will drill into details behind the numbers they see. i got this to work with itemClick and i found some good code to use for totaling the datagrid numbers by using the code from Alex's Flex closet http://blogs.adobe.com/aharui/2008/03/flex_3_datagrid_footers.html
    my problem is i'm finding that i cannot use the styling or itemClick function to work with the  footers and so am trying to subclass another footerdatagridcolumn to  have a mouse click event to do something with. i'd like for the footer data to be blue and underlined as well if thats possible but not sure how to refer to my Flex css style in AS3. see the attached screenshot i'm trying to get the footer to work with itemClick and have the same style of blue and underlined for the columns that are highlighted below.

    DataGridColumns do not dispatch mouse events.  I would listen to the
    DataGrid and use mouseEventToItemRenderer as needed.

  • Sub-class objects changing lovu2019s in XI 3.0

    Hello all,
    I have a XI 3.0 universe where I have several classes and sub-classes like this;
    Class1
    ....Subclass1
    .............Object 1
    .............Object 2
    .............Object 3
    ....Subclass2
    .............Object 4
    .............Object 5
    .............Object 6
    ...Subclass3
    .............Object 7
    .............Object 8
    .............Object 9
    Class2
    ....Subclass1b
    .............Object 10
    .............Object 11
    .............Object 12
    While updating the objects lovu2019s (for sorting) in the properties window, Iu2019ve noticed that beginning with Object 4 that the lovu2019s are changing back to that of Object 1, this is also the case for Object 5 (changes to Object 2u2019s lov) all the way through Object 12. It seems that no mater how often I set and apply the sorted lov for all objects, they take on the settings of the objects in the first sub-class in my universe. When querys are ran from WebIntelligence, they display the correct SQL (and return no results as there is no data in my dev database as yet). Objects in other classes (not sub-classes) seem to be fine. Has anyone seen this type of behavior before?
    Iu2019m thinking that I will need to go to 3.1 and suspect this may be a bug, any thoughts or comments are appreciated....

    Hi Didier,
    I did copy some some of the objects from a subclass to another, and to make sure this was not the issue, I re-created new ones and had the same issue.  I was not aware that previous BOE versions (LOVs) had the issue though, which makes some sense. 
    At the moment, I'm suspecting this is a bug so I am asking the client to upgrade to 3.1 to see if the issue persist (I suspect it may), if so I will then open up a tech support case.
    Thanks, Joe Szabo

  • Is it possible to OVERLOAD a super-class method in a sub-class?

    Hi all,
    I have a query that
    Is it possible to OVERLOAD a super-class method in a sub-class?
    If it is possible, please give me an example.
    Thanks,
    Hari

    Hi,
    Is the method int Display(int a){} overloading
    the super-class's void Display() method? If
    possible, please clarify this and how it would be
    method overloading?
    hanks,
    Hari
    Hi Hari,
    Yes, it is possible. Look at this piece of code:
    class Senior
         void Display()
              System.out.println("Super class method");
    class Junior extends Senior
         int Display(int a)
              System.out.println("Subclass method: "+a);
              return(a+10);
         }> }
    class example
         public static void main(String args[])
              Junior j = new Junior();
              j.Display();
    System.out.println("Subclass method
    od "+j.Display(5));
    Is this what you were asking? Hope this helped.Hi,
    I guess you guys are confused here...
    Overloading is achieved by methods in the same class...
    Overriding is across a superclass subclass methds.

  • Servicegen for sub-class inside vector variable of Super

    java.lang.NoSuchMethodError
    at com.netsboss.WSBE.model.QueryItemCodec.typedInvokeGetter(QueryItemCod
    ec.java:87)
    at com.netsboss.WSBE.model.QueryItemCodec.invokeGetter(QueryItemCodec.ja
    va:56)
    at weblogic.xml.schema.binding.BeanCodecBase.gatherContents(BeanCodecBas
    e.java:295)
    at weblogic.xml.schema.binding.CodecBase.serializeFill(CodecBase.java:25
    3)
    at weblogic.xml.schema.binding.CodecBase.serialize(CodecBase.java:195)
    at weblogic.xml.schema.binding.RuntimeUtils.invoke_serializer(RuntimeUti
    ls.java:184)loop
    at weblogic.xml.schema.binding.RuntimeUtils.invoke_serializer(RuntimeUti
    ls.java:170)
    QueryItem {
    private Vector airItiners;
    public Vector getAirItiners() {
    return airItiners;
    public class AirItinerary implements Serializable{}
    QueryItem is my return class. The return result will include sub class AirItinerary
    in QueryItem's Vector. I notice servicegen will only generate stub and web.xml
    for QueryItem.
    I get above error, when the result return to client. How to generate necessary
    sub-class inside a vector variable of Super class?
    Stephen

    Hi Stephen,
    write my own ser/deser? Any other quick way?Our excellent support group ([email protected]) may be able to help with
    an alternative solution. If you could create a small reproducer, then
    this will help them with a clear picture of your goal.
    One more problem, wls deloy my WSBE.ear as a war correctly. But error show noDouble check the console log for any messages. Also try:
    http://[host]:[port]/[contextURI]/[serviceURI]
    See: http://edocs.bea.com/wls/docs70/webserv/client.html#1051033 and
    also check the console to verify the app is or is not deployed. See:
    http://edocs.bea.com/wls/docs70/programming/deploying.html
    HTHs,
    Bruce
    Stephen Zeng wrote:
    >
    Hi Bruce:
    Our company use wsl7.0. We are not able to update to wls8 in this project. Do
    I have to
    write my own ser/deser? Any other quick way?
    sub class variable:
    public class AirItinerary implements Serializable{
    private String air;
    private Vector flightItem; //sub class of AirItineray
    One more problem, wls deloy my WSBE.ear as a war correctly. But error show no
    deloyment found. web-services.xml has been generated by servicegen under web-inf
    path. Thanks Bruce.
    Stephen
    Bruce Stephens <[email protected]> wrote:
    Hi Stephen,
    The java.util.vector should be converted to a SOAP Array, see:
    http://edocs.bea.com/wls/docs81/webserv/assemble.html#1060696 however
    the issue of the sub-class is most likely the problem. Can you simplify
    the data types? You may just have to write your own ser/deser, see:
    http://edocs.bea.com/wls/docs81/webserv/customdata.html#1060764
    This is with WLS 8.1, right?
    Thanks,
    Bruce
    Stephen Zeng wrote:
    java.lang.NoSuchMethodError
    at com.netsboss.WSBE.model.QueryItemCodec.typedInvokeGetter(QueryItemCod
    ec.java:87)
    at com.netsboss.WSBE.model.QueryItemCodec.invokeGetter(QueryItemCodec.ja
    va:56)
    at weblogic.xml.schema.binding.BeanCodecBase.gatherContents(BeanCodecBas
    e.java:295)
    at weblogic.xml.schema.binding.CodecBase.serializeFill(CodecBase.java:25
    3)
    at weblogic.xml.schema.binding.CodecBase.serialize(CodecBase.java:195)
    at weblogic.xml.schema.binding.RuntimeUtils.invoke_serializer(RuntimeUti
    ls.java:184)loop
    at weblogic.xml.schema.binding.RuntimeUtils.invoke_serializer(RuntimeUti
    ls.java:170)
    QueryItem {
    private Vector airItiners;
    public Vector getAirItiners() {
    return airItiners;
    public class AirItinerary implements Serializable{}
    QueryItem is my return class. The return result will include sub classAirItinerary
    in QueryItem's Vector. I notice servicegen will only generate stuband web.xml
    for QueryItem.
    I get above error, when the result return to client. How to generatenecessary
    sub-class inside a vector variable of Super class?
    Stephen

  • Can we chagne Super class method parameters in Sub class

    Hi,
    I created a super class.  In that class i created a method. That method is having 4 input parameters and 4 export parameters.
    I created a sub class for that super class. I need to use only 2 input parameters in this class rather than 4 parameters. I want to delete 2 Input parameters in the sub class of the super class method.  Is it possible.
    If possible. can we give an simple code or pseudo code?
    regards,
    krishna

    Hi,
    I think you can not.
    Because, only public attributes can be inherited and they will remain public in the subclass.
    for further detail check,
    http://help.sap.com/saphelp_nw70/helpdata/en/1d/df5f57127111d3b9390000e8353423/content.htm
    regards,
    Anirban

  • Instantiation of similar object over a super class deciding the sub class

    Hello all
    First, sorry if I'm duplicating an already answered question. I didn't searched very deep.
    Initial position:
    I have 2 Object (A1 and A2) which share the most (about 90%) of their instance variables an the associated methods. The values of the instance variables are retrieved in the real implementation from a stream. Depending of the data of the stream, I have to instantiate either a A1 or A2 object.
    A test implementation (using an int in case of the stream):
    The super class A:
    package aaa;
    public class A
      protected int version = -1;
      protected String name = null;
      protected AE ae = null;
      protected A()
      protected A(int v)
        // Pseudo code
        if (v > 7)
          return;
        if (v % 2 == 1)
          this.version = 1;
        else
          this.version = 2;
      public final int getVersion()
        return this.version;
      public final String getName()
        return this.name;
      public final AE getAE()
        return this.ae;
    }The first sub class A1:
    package aaa;
    public final class A1 extends A
      protected A1(int v)
        this.version = v;
        this.name = "A" + v;
        this.ae = new AE(v);
    }The second subclass A2:
    package aaa;
    import java.util.Date;
    public final class A2 extends A
      private long time = -1;
      protected A2(int v)
        this.version = v;
        this.name = "A" + v;
        this.time = new Date().getTime();
        this.ae = new AE(v);
      public final long getTime()
        return this.time;
    }Another class AE:
    package aaa;
    public class AE
      protected int type = -1;
      protected AE(int v)
        // Pseudo code
        if (v % 2 == 1)
          this.type = 0;
        else
          this.type = 3;
      public final int getType()
        return this.type;
    }To get a specific object, I use this class:
    package aaa;
    public final class AFactory
      public AFactory()
      public final Object createA(int p)
        A a = new A(p);
        int v = a.getVersion();
        switch (v)
        case 1:
          return new A1(v);
        case 2:
          return new A2(v);
        default:
          return null;
    }And at least, a class using this objects:
    import aaa.*;
    public final class R
      public static void main(String[] args)
        AFactory f = new AFactory();
        Object o = null;
        for (int i = 0; i < 10; i++)
          System.out.println("===== Current Number is " + i + " =====");
          o = f.createA(i);
          if (o instanceof aaa.A)
            A a = (A) o;
            System.out.println("Class   : " + a.getClass().getName());
            System.out.println("Version : " + a.getVersion());
            System.out.println("Name    : " + a.getName());
            System.out.println("AE-Type : " + a.getAE().getType());
          if (o instanceof aaa.A2)
            A2 a = (A2) o;
            System.out.println("Time    : " + a.getTime());
          System.out.println();
    Questions:
    What would be a better way to encapsulate the logic into their respective objects ? Is there a way to let the super class A itself identify the type of the object and then extend from A to either A1 or A2 ?
    Thanks in advance
    Andreas

    Hello jduprez
    First, I would thank you very much for taking the time reviewing my problem.
    Just for the record: have you considered regular serialization? If you control the software at both ends of the stream, you could rely on standard serialization mechanism to marshall the objects and unmarshall them automatically.In my case, I can't control the other site of the stream. At the end, the data comes from a FileInputStream and there aren't objects on the other site, only pur binary data.
    - It seems you have one such factory class. Then you already have encapsulated the "determine class" logic, you don't need to add such logic in superclass A.I thought from an OO view, that the super class A is responsible of doing that, but that's where the problem starts. So at the end, it's better doing it in the factory class.
    - A itself encapsulates the logic to load its own values from the stream.
    - A1 and A2 can encapsulate the logic to load their own specific value from a stream (after the superclass' code has loaded the superclass' attributes values).
    My advise would be along the lines of:
    public class A {
    .... // member variables
    public void load(InputStream is) {
    ... // assign values to A's member variables
    // from what is read from the stream.
    public class A1 extends A {
    ... // A1-specific member variables
    public void load(InputStream is) {
    super.load(is);
    // now read A1-specific values
    public class AFactory {
    public A createA(InputStream is) {
    A instance;
    switch (is.readFirstByte()) {
    case A1_ID:
    a = new A1();
    break;
    case A2_ID:
    a = new A2();
    break;
    a.load(is);
    }The example above assumes you have control over the layout of the data in the stream (here for a given A instance, the attributes defined in A are read first, then come the subclass-specific attributes.
    The outcome is: you don't have to create a new A( ) to later create another instance, of a subclass.I like the idea. In the AFactory, is the "A instance;" read as "A a;" ?
    Is there a way to let the super class A itself identify the type of the object and then extend from A to either A1 or A2 ?Note I initially read this question as "can an instance of a class mutate into another class", to which the answer is no (an object has one single, immutable class; it is an instance of this class, and of any superclass and superinterface, but won't change its class at runtime).Yes, I have been thinking about a way for mutating into a subclass to keep the already initialized values from the A class without copying or parsing again. But preventing an instance of an A class will be my way. So, in this aspect, Java didn't changed in the last 10 years... It's a long time ago I've used Java for some real projects.
    You can, however, create an instance of another class, that copies the values off a priori A instance. Your example code was one way, another way could be to have a "copy constructor":
    public class A {
    public A(A model) {
    this.att1 = model.att1;
    this.att2 = model.att2;
    public class A1 {
    public A1(A model) {
    super(model);
    ... // do whatever A1-specific business
    )Still, I prefer my former solution less disturbing: I find the temporary A instance redundant and awkward.Nice to know. I prefer the first solution too.
    Thank you again for the help and advices. My mind is searching sometimes for strange solutions, where the real is so close ;-)
    Andreas

  • Trouble assigning sub class to super class array

    Hi,
    I would greatly appreciate some help with the following:
    I want to assign a sub class to a super class array but the following code does not work
    where the board is comprised of the super class
         private static void makeMove( int X, int Y, int moveX, int moveY )
              ChessPiece tempChessPiece = ( ChessPiece ) board[ X ] [ Y ];
              board[ X ] [ Y ].setType( UNDEFINED );
              board[ moveX ] [  moveY  ] = tempChessPiece;
         }

    I have got this code to work but it does not appear
    to be very efficient to me as i dont recycle the
    objects.
    Any thoughts?The objects will be recycled by the garbage collector. It's very efficient so there's very little performance penalty in creating objects and releasing objects.
    Still, another alternative is to represent an empty square with null. In that case the code becomes,
    private static void makeMove( int selectedX, int selectedY, int moveToX, int moveToY ) {
       board[moveToY][moveToX] = board[selectedX][selectedY]; // piece to new position
       board[selectedX][selectedY] = null; // remove from old
    }I don't know your exact design but that should work. It's kind of natural too. If a square is empty there's no piece object there at all. No new object has to be created and that explicit cast is gone.

  • Sequence creation for Super Type and Sub Type (Parent-Child)

    Data Model is structured with Super Type-Sub Type Concept.When data is being inserted in the Super Type table, I will be using a sequence Supertype.NEXTVAL as Primary Key.Now the same sequence will be the Primary Key for Sub Type table also. Can I use Supertype.CURRVAL during insertion in Sub Type table?
    If Yes, I have lot of records being created in Super Type table within a second. So before data is being inserted in Subtype table there may be chance of a row being inserted in Super Type table and if I use Supertype.CURRVAL it may lead to wrong data.
    How can I make sure that Supertype Primary Key is being inserted as Primary key in sub type table?

    What happens when you try it? Something like:
    session1> select t_seq.nextval from dual;
       NEXTVAL
         40061
    session2> select t_seq.nextval from user_objects;
       NEXTVAL
         40062
         40063
         40064
         <snip>
         40270
         40271
         40272
    211 rows selected.
    session1> select t_seq.currval from dual;
       CURRVAL
         40061john

  • Accessing a Sub class variable in a Super Class

    Hi ,
    Is there any easiest way to access a Subclass Variable in a Super Class.
    Class Super1{
    Class sub extends Super1
    private String substring1;
    In my application the 'substring1' values is not null .But all fields in Super1 class are null .
    How can i access the value of the Subclass Variable in Super class .
    Thanks

    This would be a way to make the superclass dependent on subclass behavior. Of course this only makes sense if getSubString() is likely to have multiple different implementations in different subclasses.
    public abstract class Super {
      public String getString() {
       return "SuperString" + getSubString();
      protected abstract String getSubString();
    public class Sub extends Super {
      private String substring;
      protected String getSubString() {
       return substring;
    }Using this just to access a variable whose contents differ from subclass to subclass is overkill. If you want each subclass to provide a different substring, create a constructor with a substring parameter in the superclass instead:public class Super {
      private String substring;
      protected Super(String substring) {
       this.substring = substring;
      public String getString() {
       return "SuperString" + substring;
    public class Sub extends Super {
      public Sub() {
       super("substring");
    }

  • Can we change the Super class attribute scope in Sub class

    Hi.
    I created a super class. In that i have 4 attributes. That attributes are PUBLIC.
    I created a sub class. In that i got all super class attributes. I want to change that attributes as a Private. Is it possible.
    If it is possible.Give me an Example with code or Pseudo code.
    Regards.
    Krishna.

    Hi Krishna,
    It is not possible... If you declare the Attributes again in Subclass of the same name as that of Super class
    then the way of accessing them would be different from that of attributes in the main class.
    Hope this would help you
    Good luck
    Narin

  • What are exception class and persistant class?

    hi,
    what are exception class and persistant class?
    how are they different from the normal class?
    Regards,
    Anil

    Hii!
      Persistent Classes
    To use the Persistence Service for objects, the classes of these objects must be created as persistent classes in the Class Builder. The term persistent class does not imply that a class is persistent. (As a template for objects, every class is persistent). Rather, it means that the objects of that class and their state are managed by the Persistence Service. For example, the objects of these classes are instantiated in the ABAP program with a method of the Persistence Service, which ensures that the initialization is correct (not with the usual CREATE OBJECT statement). When the Class Builder creates a persistent class, it automatically generates an associated class, known as the class actor or class agent, whose methods manage the objects of persistent classes. As well as their identity, persistent classes can contain key attributes, which allow the Persistence Service to ensure that the content of each persistent object is unique.
      Check out this link
    http://www.sapnet.ru/abap_docu/ABENABAP_EXCEPTION_CLASSES.htm
    Regards
    Abhijeet

Maybe you are looking for