Constructor method handling

I'm not sure how to handle the behaviour of a constructor method.
I have a constructor in a class that calls native function via jni to initialize a device. If native function call fails for some reason, I make it throw an exception (NativeFailureException which I defined).
But I'm not sure how to handle that correctly in my constructor. Should I declare constructor method so that it throws (then propagates) the same exception to the user of my object, or should I handle internally the exception and maybe block the execution of the code? (if device fails to initalize, the class is useless).
Because if i declare the constructor so that it throws the exception, then every time one use my class has to place the creation of the object in a try ... catch statement and that seems not so neat to me ... what do you think?

The class will be useless since it provides an interface to the underlying c driver to the device. If the device can't be initialized by the driver, then all its methods are useless since I can't even initalize the communication between my java class and the device, via the native driver.
But the problem is, if I catch the exception in the constructor I may have a code like this:
Class NativeDriverTest{
     main{
          NativeDriver myDriver;
          try{
               myDriver = new NativeDriver();
          }catch (Exception e){     
               System.out.println ("OMG! " + e.toString());
               System.Exit(1);
          myDriver.func(...);
}But if I try to compile the code I get an error on myDriver.func(...) call
variable myDriver might not have been initialized
Why is that an error and not rather a warning? I know that the variable "might not have been initialized" but it's my work to ensure that this doesn't happen ... why it doesn't compile?
Should I put all my myDriver calls in the try block?
Should I use another syntax?

Similar Messages

  • My constructor method is bogged!

    Hi There,
    I've got some problems with constructor methods in my program, of course the constructors look fine to me, but then faulty code usually looks good to any programmer after enough hours! Here is some of my code, firstly the following snippet shows the objects being instantiated.
    public static ButtonData BtData1;
    public static ButtonData BtData2;
    public static ButtonData BtData3;
    public static ButtonData BtData4;
    public static ButtonData BtData5;
    public static void main(String[] args)
        try{
          inStream = new FileInputStream("ObjStore");
          objStreamIn = new ObjectInputStream(inStream);
          if(objStreamIn.available() == 0)      
            objStreamIn.close();                
            inStream.close();                   
            BtData1 = new ButtonData("Link1",null);
            BtData2 = new ButtonData("Link2",null);
            BtData3 = new ButtonData("Link3",null);
            BtData4 = new ButtonData("Link4","Zero");
            BtData5 = new ButtonData("Link5","Zero");
          else
        }catch(IOException e){}
        GUI xyz = new GUI();            
    }Alot of the above code is related to serialization -- mainly checking to see whether or not objects already exist on file, and if they do not, instantiating them. Notice that the above constructors have different parameters or arguments (I can't remember which word describes it best!) -- it doesn't seem to matter whether I use two strings such as ("Link4","Zero") or ("Link1",null) -- both create errors. The class that is instantiated looks like this:
    import java.io.*;
    public class ButtonData implements Serializable
      String Name;             
      String Path;             
      ButtonData(String Name,String Path)
        this.Name = Name;
        this.Path = Path;
      protected String getName()
        return Name;
      protected String getPath()
        return Path;
      protected void setName()
        Name = Begin.LinkName.getText();
      protected void setPath()
        Path = Begin.ExecT.getText();
    }As far as I can tell the constructor above follows all the relevant syntax rules, as does the first snippet of code that I provided -- where the objects are instantiated. I will probably feel like a real meat head if I have done something dump and obvious, however I have double checked the code and it looks fine to me. When trying to compile the code I get the following error messages (using JBuilder7) -- these error messages highlight the relevant sections of the first code snippet I provided:
    "Begin.java": Error #: 300 : constructor ButtonData(java.lang.String, null) not found in class quicklauncher2.ButtonData at line 61, column 23
    "Begin.java": Error #: 300 : constructor ButtonData(java.lang.String, null) not found in class quicklauncher2.ButtonData at line 62, column 23
    "Begin.java": Error #: 300 : constructor ButtonData(java.lang.String, null) not found in class quicklauncher2.ButtonData at line 63, column 23
    "Begin.java": Error #: 300 : constructor ButtonData(java.lang.String, java.lang.String) not found in class quicklauncher2.ButtonData at line 64, column 23
    "Begin.java": Error #: 300 : constructor ButtonData(java.lang.String, java.lang.String) not found in class quicklauncher2.ButtonData at line 65, column 23If anybody can shed some light on what is going on here it will be greatly appreciated.
    Thanks

    Thanks everybody for your kind constributions, unfortunately I have tried all suggestion provided and have come up with naught. As both classes are in the same package, the question of scope is resolved, and making the ButtonData objects constructor public has no effect on the error messages displayed. I have also modified the ButtonData class so that accessor and mutator methods are public and variables are private, unfortunately this also has had no effect on the immediate error messages. If anybody has further suggestions they will be greatly appreciated. I thought perhaps that the issue with the constructor may be related to the implementation of the serializalbe interface ----->
    beyond that idea I am seriously stuck!

  • Declaring constructor method public or private.  What's the point?

    My book declares the constructor method public. I tried declaring it private, and without any modifier out of curiousity. It runs exactly the same. What's the point of doing so?
    public class test
         public static void main( String[] args )
              test fun = new test();
              test fun2 = new test(2);     
              System.out.println( fun );
    //          System.out.println( test.toString() );
         public String toString()
              return "This is the toString";
         test()
              System.out.println( "This is the constructor method" );
         test( int x )
              System.out.println( "This is the constructor method: " +x );
    }

    yougene wrote:
    I'm new to OOP so maybe I'm not completely grasping the terminology. But this program works just fine with my class.
    public class test2
         public static void main( String[] args )
              test foo = new test();
    }It gives me the following output
    ----jGRASP exec: java test2
    This is the constructor method
    ----jGRASP: operation complete.The constructor method is executing from an outside class. I tried this with and without the private modifier on the constructor. Same result.Try compiling this.
    public class C1 {
      private C1() {
        System.out.println("C1 c'tor");
    public class C2 {
      public void foo() {
        C1 c1 = new C1();
    }

  • Constructor method, Can you easily solve the issue?

    I have had many problems intergrating a constructor method into my program. This is my first time programming in java, can someone please help me. I have contructed a class for an airplanelisttester, that allows the user choice to add or remove planes from the program using a switch method, i have yet to program each "case" accordingly, but i am having trouble at the start of the code. I need to create an "airplanelist" object, i have found some help on the internet, but i am not sure what is going wrong.
    public class AirplaneListTester
         public static void main (String[] args)
    throws java.io.IOException
              char choice;
              int size;
              size = EasyIn.getint();
         AirplaneList plane = new AirplaneList();
         plane.add(Airplane) = "Add a plane?";
         plane.remove(int) = "Remove a plane?";
         plane.isEmpty() = "Is Empty";
         plane.isFull() = "Is Full";
         plane.getitem(int) = "Airplanenumber";
         plane.getTotal() = "size" ;
         public AirplaneList
         private boolean add(Airplane);
         private boolean remove(int);
         private boolean isEmpty();
         private boolean isFull();
         private int getitem(int);
         private int getTotal();
         //..............rest of the program using swtich comands to alow the user to add\remove an airplane , check if a list is empty or      //full and display the list as well as exit the program.
    }

    ok so it should look a little like this? I am not really sure, on how to create these objects? ;-<. I understand that "isEmpty" and "isFull" should bounce back very obvious boolean statements, i.e. isfull or isempty. However I am not sure on what values to initiate for "add(Airplane)" ? Is that null? or should i prompt the user to enter one?
    import javax.swing.JOptionPane;
    public class AirplaneList
         public static void main (String[] args)
    throws java.io.IOException
              char choice;
              int size;
              size = EasyIn.getint();
         AirplaneList plane = new AirplaneList();
         plane.add(Airplane) = "Add a plane?";
         plane.remove(int) = "Remove a plane?";
         plane.isEmpty() = "Is Empty";
         plane.isFull() = "Is Full";
         plane.getitem(int) = "Airplanenumber";
         plane.getTotal() = "size" ;
    //declaration
    private boolean add(Airplane);
    private boolean remove(int);
    private boolean isEmpty;
    private boolean isFull;
    private int getitem(int);
    private int getTotal;
    //constuctor
    public AirPlaneList
    add(Airplane) = null;
    remove(int) = null;
    isEmpty = true;
    isfull = false;
    getitem(int) = size;
    getTotal = null;      //initialisation
    //methods
    public boolean isFull()
    return isfull;
    public boolean isEmpty()
    return isEmpty;
         //..............rest of the program using swtich comands to alow the user to add\remove an airplane , check if a list is empty or      
    //full and display the list as well as exit the program.
    }

  • Constructor Method parameter problem

    I write my class whit this constructor method.
    public Immobile(int id, String complesso, String tipoed,double prezzo) {
    this.id = id;
    this.complesso = complesso;
    this.tipoed =tipoed;
    this.prezzo = prezzo;
    in my app i want to create an object of Immobile class:
    Immobile imm = new Immobile(1,"nuovo",null,2);
    Always is ok
    if I don't want to pass the String parameter I set it whit null.
    But if I don't want to pass an integer like first parameter, or double like prezzo parameter, How can I do this?
    I don't want to use Overloading of method because if the Immobile class have for example 30 parameter, i don't want to write 30 constructor method.
    There is any possibility?

    I think that my design is ok.Two competent developers and me disagree with you.Sign me in here. Every time I get code with methods with more than 4 parameters I shudder.
    A class with 30 constructor parameters is probably a class with 30 fields and more often than not those class fields can be refactored in smaller classes, like ...
    I think that made a class User whit parameter Name,
    Surname, address, telefon, fax is ok
    and i think that a user probably haven't a fax.
    I think that one way can be to use all the parameter
    like String, that accept null, next, casting orsome
    conversion before insert in a database
    What do you think about this?Surname, address, telephone and fax give you 30
    variables? What are you doing, show a small piece of
    relevant code....
    class ContactInfo class for tel, fax, mail, pager.
    class Adress for City, street, country, etc.
    and so on.
    I don't know if BiggDaddy 's sugestion comes in hand in any problem solution but I know that it can very easily come out of hand, I worked on a system where everything was passed down through 2 parameters, that where in fact 2 arrays of parameters.
    The system was a mess, very hard to understand and to test, and bugs popped around in production time.
    May the code be with you.

  • Constructor methods

    Is it absolutely necessary to have a constructor method in a class? I realise it might not be good programming practice, but would be glad of any opinions.

    Every class always has at least one constructor. If you don't provide one explicitly, the compiler inserts one that takes no arguments and does nothing but call the superclass' no-arg constructor.
    http://java.sun.com/docs/books/tutorial/java/javaOO/constructors.html
    Constructor rules:
    1) Every class has at least one ctor.
    1.1) If you do not define an explicit constructor for your class, the compiler provides a implicit constructor that takes no args and simply calls super().
    1.2) If you do define one or more explicit constructors, regardless of whether they take args, then the compiler no longer provides the implicit no-arg ctor. In this case, you must explicitly define a public MyClass() {...} if you want one.
    1.3) Constructors are not inherited.
    2) The first statement in the body of any ctor is either a call to a superclass ctor super(...) or a call to another ctor of this class this(...) 2.1) If you do not explicitly put a call to super(...) or this(...) as the first statement in a ctor that you define, then the compiler implicitly inserts a call to super's no-arg ctor super() as the first call. The implicitly called ctor is always super's no-arg ctor, regardless of whether the currently running ctor takes args.
    2.2) There is always exactly one call to either super(...) or this(...) in each constructor, and it is always the first call. You can't put in more than one, and if you put one in, the compiler's implicitly provided one is removed.

  • Difference between constructor & Methods if any ?

    In the below code I use the constructor ConstructorShirt1('M') to pass the value of M to the class ConstructorShirt1, but why do we have to do this, instead can we not just use a method and write the same thing in a method.
    class ConstructorShirt1Test {
         public static void main (String args[]) {
    ConstructorShirt1 constShirt = new ConstructorShirt1('M');
    char colorCode;
              colorCode = constShirt.getColorCode();
    System.out.println("Color Code: " + colorCode);
    class ConstructorShirt1 {
    private int shirtID = 0; // Default ID for the shirt
    private String description = "-description required-"; // default
    // The color codes are R=Red, B=Blue, G=Green, U=Unset
    private char colorCode = 'U';
    private double price = 0.0; // Default price for all items
    private int quantityInStock = 0; // Default quantity for all items
    public ConstructorShirt1(char startingCode) {
    switch (startingCode) {
    case 'R':
    case 'G':
    case 'B':
    colorCode = startingCode;
    break;
    default:
    System.out.println("Invalid colorCode. Use R, G, or B");
    public char getColorCode() {
    return colorCode;
    } // end of class
    So I am not clear what is the difference between constructor and methods if any ? or if not when to use a constructor and when to use a method.
    I would be glad if somebody throws light on this topic.
    PK

    There shouldn't be any confusion on this one... a constructor is meant to create an instance of the class. It can also set the state of its member variables in the process, like the constructor you are using. The same can also be done by a method.
    Wouldn't make much of a difference for simple programs, but this is more pertinent when it comes to designing classes. Like if the developer using the class needs to know what all states he has to set before he needs to do anything useful, then it is better to provide a constructor with some arguments for doing that.

  • HTTP delete method handling / enabling??

    Hi, I am a newbie to the WL world and wondering if there is any setup/config required on the weblogic server to enable the handling of HTTP DETELE method or does it all control/manage by the application? I understand web servers like Apache requires specific setup/scripts to handle the DELETE method. What about WebLogic Srvr?

    To enable delete, there must be "modify"permission
    given to the user account who has access to web
    application. By default "IUSR_machinename" windows
    account has anonymous access to web application in
    IIS. You must have to give "modify" permission to
    this acccount on the web application folder.
    That's it !!!!! You are ready to send HTTP DELETE
    requestsUmmmmmm. This seems a greatly dangerous and stupid
    solution!I mean this topic is completely out of scope for this forum and I know not a whole lot about IIS but it seems to me you just set it up so anyone can delete files from your website.
    Did you really want to do that?

  • Recalling up main() or method handling maybe??

    I have the following code which has a menu in main and the methods related to this method.
    import javax.swing.*;
    import java.util.*;
    import java.io.*;
    public class Sport
    public static void main (String[] args)
    try     
                   String menu = JOptionPane.showInputDialog(   //This the menu the user see's
                   "Select 1 to input results\n"+
                  "Select 2 to linearsearch\n"+
                  "Select 3 to Check contents of  array\n"+
                  "Select 0 to Quit");
              int menu2=Integer.parseInt(menu);
              if (menu2==1)           //i use if statements to match the methods with the menu
                 inputteams();
              if (menu2==2)
                   linearsearch();
              if (menu2==3)
                   printArray();
              else
                   System.exit(0);
         catch (IOException e)
                   System.err.println("Caught IOException: "+ e.getMessage());
    public static void inputteams()throws IOException
         resultList myList = new resultList();
         int count = 0;
         int stillContinue= JOptionPane.YES_OPTION;
            while (stillContinue == JOptionPane.YES_OPTION)
             String na = JOptionPane.showInputDialog("Please, enter team name");
             String da = JOptionPane.showInputDialog("Enter date:");
              String sc = JOptionPane.showInputDialog("Please enter score");
        if (na!=null && da!=null && sc!=null)
              result data = new result(na, da, sc);
             myList.insert(data);
            stillContinue = JOptionPane.showConfirmDialog(null, "Enter another record?",
                              "???", JOptionPane.YES_NO_OPTION);
              count++;
         public static void printArray() 
        resultList myList = new resultList();
        result[] myArray = myList.getResult(); 
        for( int i=0; i<myArray.length; i++)
                 result myResults = myArray;
              if( myResults != null )
    System.out.println("Database contents" + myArray.toString());
    else
    System.out.println(""); //Handling empty elements in the array
    }               //to avoid return of nullPointer
    }Now it starts of asking the user for their choice from the menu.  When they enter their choice the appropiate method comes up for the entered choice.  When the user finishes with completing their choice the application closes.  What i need to do is return back to the menu everytime.
    So for example, if at the main menu the user enters 1, they will be inputting information about their team.  They can repeat inputting until the NO option is choosen on the input dialog.  Once this is choosen, the user should then once again be presented with the menu option.  How would i go about doing this?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Check out the while loop in your main method below...
    It will keep looping around your code till the boolean variable alive becomes false and the only place it can become false is when the user has not chosen one of your menus.
         public static void main (String[] args)
              boolean alive = true;
              try     
                   while (alive)
                        String menu = JOptionPane.showInputDialog(   //This the menu the user see's
                                  "Select 1 to input results\n"+
                                  "Select 2 to linearsearch\n"+
                                  "Select 3 to Check contents of  array\n"+
                        "Select 0 to Quit");
                        int menu2=Integer.parseInt(menu);
                        if (menu2==1)           //i use if statements to match the methods with the menu
                             inputteams();
                        if (menu2==2)
                             linearsearch();
                        if (menu2==3)
                             printArray();
                        else
                             alive = false;
              catch (IOException e)
                   System.err.println("Caught IOException: "+ e.getMessage());
         }Hope this helps...
    [email protected]

  • Reg Servlet's inti method and Constructor method

    Hi,
    My friend asks me 'Is init method of servlet is necessary? Can't we do whatever we want to do in Init method, in the constructor of the servlet? Why is init method is necessary?'
    Thanks in advance,
    Guhan

    you can get the config object from the init method which u cant get from constructors. The environment details of the servlet can be had from it...

  • Overriding Constructor Method

    Hello,
    I want to write a class that heritances behaviour and porpoerties of the superclass. Is it possible to execute the methods of the superclass in the subclass? Instead I could write a method in the superclass and call it inside constructor of the subclass, but that seems like a trick to me.

    Is it possible to execute the methods of the superclass in the
    subclass? Instead I could write a method in the superclass and call it
    inside constructor of the subclass, but that seems like a trick to me.
    If you are talking about calling super class constructor in subclass, you can do that:
    public function SubClassConstructor(){
         super();
    If you need to call function of superclass, well, you have to write it in superclass, right? Just make it either public or protected.

  • How are Travelex Payment Method handled in AP?

    Hi
    I would like to know if there are any Outbound/Inbound extracts related to Travelex?
    Thanks
    Ranjani

    Hi,
    SPRO>>IMG>>Financial Accounting(New)>>Accounts receivable and Account payable>>Business transactions>>Automatic Outgoing payments>>Set Up payment Payment methods per country for payment transactions>>
    Step 1>> Select your Country for e.g. IN
    Step 2>> Select an existing entey>>Copy as new entry
    Step 3>> Change the description and change in Posting details tab e.g Document type for payment RE.
    Please revert for queries.
    Rgds,
    Harmees
    Points if useful!!!!

  • How are static methods handled in a multithreaded application?

    hi
    i have a class Drawer with a static method public static draw(Graphics g). now assume there are more thrads callin at the same time Drawer.draw(g). What happens? have some threads to wait until the others have finished calling the method, or can static methods be multithreaded, (can they perform simultaniously)?
    thanks, jo

    ups, i am not drawing on the screen, but in every thread i am drawing a Image. this means before i call the static method in every thread there will be created a BufferedImage and then i pass the Graphics from this images to the static method. also in this case the method performs simultaniously? every thread has its own image and graphics, so the static method should be perform at the same time, isn't it?

  • Can't get stage from a constructor method. Why?

    Hi,
    I'm making a kind of image showcase, what has a fluid width and height, depending on browser window dimensions. Everything is okay, I have other kind of issue: in constructor function in this gallery class I can't use stage property, I have to get it from main class.
    Why Flash treats me this way and how I can avoid this currentStage variable?
    Main code:
    package dev {
         import flash.display.Sprite;
         import flash.display.StageScaleMode;
         import flash.display.StageAlign;
         import flash.display.MovieClip;
         import flash.events.Event;
         import UI.BackgroundImageRotator;
         public class Application extends Sprite {
              public function Application():void {
                   stage.scaleMode = StageScaleMode.NO_SCALE;
                   stage.align = StageAlign.TOP_LEFT;
                   trace("Start.");
                   var BIR = new BackgroundImageRotator(stage);
                   stage.addChild(BIR);
    BackgroundImageRotator class:
    package UI {
         import flash.display.MovieClip;
         import flash.events.Event;
         import flash.display.Stage;
         public class BackgroundImageRotator extends MovieClip {
              protected var currentStage:Stage;
              public function BackgroundImageRotator(currentStage:Stage):void {
                   this.x = 0;
                   this.y = 0;
                   this.currentStage = currentStage;
                   currentStage.addEventListener(Event.RESIZE, onStageResize);
              protected function onStageResize(evt:Event):void {
                   trace(stage.stageWidth + ' ' + stage.stageHeight);

    if you have a display object that will be added to the display list, you need to wait until it is added before you can reference its stage property.  ie, use the Event.ADDED_TO_STAGE event.
    otherwise, you must pass a stage reference to your class.

  • A method handling several kinds of exceptions

    Hello there!
    I want to create a method that enables me to log several different kinds of exception... I used this code as for my method:
    public void myExceptions(Exception ex){
              try{
                   File file1 = new File("exceptions.txt");
                   boolean success1 = file1.createNewFile();
                   if (success1){
                        BufferedWriter bw1 = new BufferedWriter(new FileWriter(file1));
                        bw1.write(String.valueOf(ex)+"\n");
                        bw1.close();
         }It works fine with Exception but not with every other kind i work with like IOException... is there a way universalize the input type of my method so as not to create different methods for each type of exception?
    Thanks a lot!

    If you specify just the filename it will be stored in the directory which is current when the application is started. Personally I don't think that's a particularly useful place. On the other hand it's bad practice to hard-code file paths in programs. You could store a file path in, say, a properties file or the Preferences class.

Maybe you are looking for

  • Error while running  jcwde

    Hi All, I am getting an error while running even the sample program in java card kit 2.2.2 i set all the path ,classpath as mentioned in the documentation page. But when i run the jcwde as mentioned in the doc its giving a message "card was unexpecte

  • Check Partner Authorisation--Quantity Contract

    Hi, I have created a quantity contract with Sold To Party ( Partner Function SP)as 100276 and Sold To Party for release Order (  Partner Function AA)as 1000 and 100276.   I have selected Check Partner Authorisation as A in contract definition in VOV8

  • JDev migration from 9.0.3 to 10.1.2

    Hi I have migrated a BC4J Application from 9.0.3 to 10.1.2, But after compilation it is showing 0 errors and when i run the embedded oc4j server the following Message comes JBO-30003: The application pool (securityAMLocalPool) failed to checkout an a

  • Opening PDF in Illy...

    Hello, This is something that has bugged me for some time. When clients give me PDF's asking me to change the text, I end up writing it all out again which is annoying. Is there a way of connecting all the text boxes up so I don't have to spend half

  • Best Practices for information technology

    Hi All, Please suggest me the link or document, Implimenting SAP ERP and CRM for Information Technology Process (IT Services Provider)