a static reference to a URL object

I want to create a final static reference to an instance of URL:
public class SomeClass {
  static final URL rooturl = new URL(stringA); // fail. an exception is thrown but not caught.
  ...
}
If I do not end rooturl, then it works:
public class SomeClass {
  static URL rooturl;
  static {
    try {
      rooturl = new URL(stringA);
    } catch(Exception e) {...}
  }
  ....
}
I'm ok with the help of the solution of the static initializer block.
But I would like to know how to create a final static reference to an instance of a class whose every constructor throws an Exception.

I won't read all of this code, because it is irrelevant to the question I think you, and stuff on the newspapers and magazines is also irrelevant.

Your first post properly reflected your problem, I think.

public class Foo {
  private static final URL url = new URL("a://b.c"); // Your question is: What do I do if new URL() can throw a checked exception?
}

Here's the thing. When you say static private final URL url, you tell the compiler that the url variable must be assigned a value when your class loading. Now, as you saw, you can throw a checked exception to a static initializer, but that's OK, you can just wrap in the Unchecked exception, ExceptionInInitializerError, like I showed you. That's what this course is aimed at the:

public class Foo {
  try {
    private static final URl url = new URL("a://b.c");
  }
  catch (MalformedUrlExeption e) {
    throw new ExceptionInInitializerError("Could not create URL", e);
  }
}

It is a correct approach. You have already decided that this value must be initialized at class load - your class requires time in order to do its job, or if you have asserted. So if the URL cannot be created, this class can't do his job, then he expected to fail to load.

If you makes it not final, then your catch block can log the error, instead of throwing. Do you understand why? This is because the final member variables must be initialized before that code can go further. Throw the uncontrolled exception means that code is not go any further, it's legal. And for a variable not final, it is not necessary to have a value, then you can simply log in and continue.

HOWEVER, suppose make you no final, record a message and continue. Now what?

Your code continues as if everything is fine, when in fact, he's not fine. Catch the exception did not have the problem go away, and to raise once again does not, your code has no idea that something was wrong. So when you get to the point where you try to use the URL, you will get a NullPointerException. Then what? You catch that, record and continue as if everything goes well?

Some point to actually deal with the fact that an error has occurred. Does not simply continue on as if all goes well. If you have one) offer some State assistance or operation that takes the place of the problematic code (almost never a good approach), b) again, or c) propagate the error to the caller and let him face (usually approach correct).

Tags: Java

Similar Questions

  • static reference with the global variable

    Hi, I used a static reference to a Subvi where I change a global variable before (3-4 years ago) and do not remember how I did it.

    It was something like these attachments, but now I'm using LabView 2013 instead of LV 8.6.

    The change in the overall operating system sees only not in the main vi (looks like the invoke node run vi does not work with globals).

    In addition the vi close with the invoke node close vi but not if I put the custom in the Subvi properties to automatically close.

    dkfire wrote:

    Why not call the sub vi as usual, just with the setting to display the front panel, when it is called?

    Use the connector pane to transfer the value of the sub vi Ok button when done.

    That's what I recommend.  If this is not possible for some reason, then you will need to use a flat Structure of the sequence to force the reading of the global variable after the Subvi is complete.

  • How to use a static reference to maintain a VI in memory, but then call it in parallel?

    Hi all

    I have a MainVI and I want to call him a Subvi in parallel so that I can have both windows open and sensitive at the same time.  The Subvi can be closed and then reopened any number of times, but only one in existence at the same time.  I know how to do it using the reference VI opened, offering a path relative to my Subvi, check to see if its already running and if so bring window to front (using front panel: open with entries True/Standard method) and if not run it using the Invoke method: Run (and eventually open its façade by program).  This method worked very well.

    Now, I've added functional global variables in my Subvi, and I want to keep in memory inbetween opening Subvi window.  I can do this by placing a copy of the functional overall in my MainVI, even if I do not here for nothing.  It works very well.

    By chance, I came across a reference to a static reference of VI, which resembled a great improvement in my method, for the following reasons:

    1) Subvi keeps in memory all the time, eliminating the need to put the functional overall in MainVI when it is not used it.

    (2) tells the LabVIEW to include the Subvi when I build my executable, rather than me having to specifically mark as always include in the build specification.

    (3) eliminates the need to continue the path and the name of Subvi updated in a constant string in my code, in order to use the open VI reference.

    However, in trying to implement this solution, I ran into the problem that once you put a reference of VI in strictly typed static (strict typing is necessary to keep in memory) on the block diagram, that VI is reserved for execution.  This means that I can't run it using the Invoke method: Run.  I did not just put it on the diagram directly as a Subvi because I need it to run in parallel to the MainVI.  I searched through these forums extensively, and although there are several references to a static reference of VI, none of them say explicitly how to actually run this 'thing'!  : PEI

    I greatly appreciate any insight into my problem.  If I have to go back to the old way it works perfectly, but I really like the apparent elegance of this solution.  I hope that it will be technically possible, and I'm not bad understand something.

    Thank you for your help,

    -Joe


  • Get a static reference to decoration

    Is it possible to get a static reference to a decoration? I have some tips that is represented by colorful decorations that I want to change the colors of them based on the data that I get. I know, it is possible to obtain references to the decorations in a programmatic manner, but it is something huge maintainability because it is incredibly difficult to follow the course of the program. Thank you.

    I don't think you can get that directly. Check the exchange of ideas. I think that there has been a few proposals along this line.

    Perhaps another approach would be to put indicators of color behind the decorations box and change the color of those. The borders of your pipe decorations would be opaque, while the Interior would be transparent to allow the squares of color to show through. The color boxes appear as standard terminals on the block diagram. With appropriate labels, they fit perfectly in the paradigm of data flow.

    Lynn

  • Static reference of VI VI reentrant

    Is it possible to use a static reference of VI to dynamically launch a VI on the way home?

    I found this old post, http://forums.ni.com/ni/board/message?board.id=170&message.id=120367, the user can find a work around, but it of ugly, isn't it

    The last snapshot in your link shows the best way to invoke an instance of a reentrant VI dynamically. The only thing I would change from that is to use the Name of VI property instead of the Path of VI property to wire open VI return. You can simply use the name of VI if the VI is in memory, which is more effective. Since you have a static reference of VI, the VI will certainly be in memory.

    I agree that it's a bit ugly. Personally, I created a Subvi to hide the ugliness and make him feel more simple!

  • VI static references in an application using

    Hello to you all, useful forum fans!

    I use 4 different static references of VI hung directly to "Run a VI" invoke nodes, with the waiting "until" and settings "Auto have Ref" both false, run the four screws dynamically, which each does nothing except call my serial port returning from input/output VI with a different index of COM port number.  Overall it works pretty well.  However, I have a few questions concerning the improvement of my installation.

    (1) is it possible to somehow set an input parameter to the serial port environment VI and thus be able to invoke it directly four times in a loop for, each with a different input value?  I don't know how I would do that, except that I heard that you can set the value of a control on a VI by using a reference to it.  I also fear that the use of the same reference VI static to invoke the VI 4 times somehow re - start the same instance of dynamic VI 4 times, instead of spawning 4 copies of it.  However, this solution would allow me to remove the 4 screws that do nothing except call the reentrant VI, and my code would be simpler and more extensible (e.g. making it easy to interact with 8 ports in the future series just by increasing the number of for the iterations of the loop).

    (2) it seems to be necessary for me to add the 4 screws that I dynamically invoke in my lvproj file and add to the section "Still included" my generation of application properties in so that they can be included in the executable file of my application.  It was what I had to do in previous versions of my code when I've referenced via a path on the screw name, but now I've changed using static references of VI, I thought they would be included automatically.  LabVIEW already knows to automatically load them into memory (for example, when I do a search it finds them even when they are not open), and they are included in the list of dependencies in the LabVIEW project, so why they would be built to my executable?  I would prefer not to have to add explicitly, as it is one thing to forget if I change it in the future.  Is there a setting or something somewhere that I can change so that they will be included in the executable file automatically?

    I thank very you much for your time and your help as always!

    -Joe

    Hey Joe,

    Answer to Q1: Yes.  Wire one '8' (type of data I32) entry 'options' function 'open VI Reference.  This indicates 'Reference open VI' that the VI is re-entrant.  It will look like this:

    Use the resulting table of references to follow your screws laid throughout the rest of your application.  Don't forget to close them when you are finished with them.

    For the 2nd quarter... I certainly built executables by using code similar to what I show above and did not have to explicitly include the screw called statically in the build.  You're right, they should be automatically included in the compilation - mine were always, including modules that reside in a different lvproject (called by a main control VI).  Sometimes I felt it necessary to develop modules in a lvproject and then call them from different main screws that reside in other projects.  If I used a static reference, they are always included.  What LV version do you use?

  • convert datalog reference to "generate report object Referecnce.ctl".

    I inherited a LV6.1 code with a lot of reports. The former reference number of datalog used to refer to the reports has been updated report object Reference.ctl.

    In the original code, the first step is to check if the number of datalog was not "a path/number/RefNumber '. But this function no longer works with the new "report to" the object. Is there something else I can use to reproduce this function?

    Thank you.

    Hi efarr,

    I'll do what I can to help you with your problem.  First of all, I need to know what version of LabVIEW, you try to run the LV6.1 code that you have inherited.  You can try your report at the node of wiring to another function of reporting (such as programming > report generation > progress reports > get a report Type) and the error on the node of wire to the terminal case selector on the structure of your business.  If the report is Type VI Gets a bad report of signal, it should output an error which will then control the structure of the case.  Instead of 'True' and 'False' cases, we had you previously, your case will read "Error No." and "error".  Without understanding your entire application I can't be sure this work around will make your program works in the same way.

    I would like to know if it works.  I hope that you will soon be operational.

  • "Reference to the error object not set to an instance of an object."

    Why after an automatic update of windows 7, I get this error "error object not set to an instance of an object reference"?

    Hi AHurst,

    1. When you receive the error message?

    2. the updates have been installed on the computer?

    Check if the problem persists in safe mode.

    Start your computer in safe mode

    http://Windows.Microsoft.com/en-us/Windows7/start-your-computer-in-safe-mode

    Restart the computer to return to normal mode

    If the problem does not still in safe mode, and then perform the clean boot procedure to verify if a third party installed on the computer program is causing the error message.

    To help resolve the error and other messages, you can start Windows Vista or Windows 7 by using a minimal set of drivers and startup programs. This type of boot is known as a "clean boot". A clean boot helps eliminate software conflicts.

    See the link below to learn more about how to clean boot.

    How to troubleshoot a problem by performing a clean boot in Windows Vista or in Windows 7

    http://support.Microsoft.com/kb/929135

    Reset the computer to start as usual

    When you are finished troubleshooting, follow these steps to reset the computer to start as usual:

    (a) click Start, type msconfig in the search box and press ENTER.

    (b) If you are prompted for an administrator password or for confirmation, type your password or click on continue.

    (c) under the general tab, click the Normal startup option, and then click OK.

    (d) when you are prompted to restart the computer, click on restart.

    I hope this helps!

    Halima S - Microsoft technical support.

    Visit our Microsoft answers feedback Forum and let us know what you think.

  • How to get the external Bitmap of URL object

    Hi all!

    I'm a developer starting with components of BlackBerry, I try to get a Bitmap of the outer object
    URL, but my getImage method does not work correctly. I think that the problem lies in the getImage method. just at the moment where I try to
    create form of Bitmap bytes. Note: J2me with the Image object, that it works!

    could someone help me please?

    Sorry for my bad English & thank you for helping me!

    Code:

    SerializableAttribute public class MainForm extends form {}

    private String url = "http://user-xxxx/json.js";
    private String [] imageURLs = new String [5];

    public MainForm() {}

    try {}
    getJSON (url);
    } catch (IOException e) {}
    e.printStackTrace ();
    }

    try {}
    Add (GetImage(this.imageURLs[0]));
    } catch (Exception e) {}
    e.printStackTrace ();
    }
    }

    Public Sub getJSON (String url) throws IOException {}
    StringBuffer sb = new StringBuffer();
    InputStream is = null;
    HttpConnection hc = null;
    try {}
    long bytesLength = 0;
    int ch = 0;
    HC = (HttpConnection), Connector.open (url);
    is = hc.openInputStream ();
    bytesLength = hc.getLength ();
    If (bytesLength! = - 1) {}
    for (int i = 0; i)< byteslength;="" i++)="">
    If ((ch = is.read (())! = - 1) {}
    SB. Append ((Char) ch);
    }
    }
    } else {}
    While ((ch = is.read (())! = - 1) {}
    bytesLength = is.available ();
    SB. Append ((Char) ch);
    }
    }
    parseJSON (sb.toString ());
    } {Finally
    is. Close();
    HC. Close();
    }
    }

    {} public void parseJSON (String sb)
    try {}
    JSONObject jo = new JSONObject (sb);
    If (jo! = null) {}
    JSONObject channel = jo.getJSONObject ("channel");
    If (channel! = null) {}
    JSONArray points = channel.getJSONArray("item");
    If (items! = null) {}
    for (int i = 0; i)< items.length();="" i++)="">
    JSONObject point = items.getJSONObject (i);
    this.imageURLs [i] = item.getString ("image");
    }
    }
    }
    }
    } catch (Exception e) {}
    e.printStackTrace ();
    }
    }

    I think that the problem lies in this method.

    public BitmapField getImage (String url) throws Exception {}
    InputStream inputStream = Connector.openInputStream (url) (InputStream);
    Bitmap image = null;
    BitmapField bf = null;
    try {}
    ByteArrayOutputStream Baos = new ByteArrayOutputStream();
    int ch;
    While ((ch = inputStream.read ())! = - 1) {}
    Baos.Write (ch);
    }
    Byte [] imageData = baos.toByteArray ();
    Image = Bitmap.createBitmapFromBytes (imageData, 0, imageData.length, 1);
    BF = new BitmapField (image);
    } {Finally
    If (inputStream! = null)
    inputStream.close ();
    }
    return (bf == null? null: bf);
    }

    public String [] getImageURLs() {}
    Return this.imageURLs;
    }

    }

    Finally my fatal mistake was in archive JSON, I change the URL of the images of http://localhost/image.jpg to
    http://user-xxx/image.jpg (MDS - CS available in http://localhost URL: 8080 /), and now it works!

    Ted and arkadyz, your suggestions have been very helpful for me, thank you very much!

    Final code:

    Class MainMIDlet

    Import net.rim.device.api.ui.UiApplication;

    SerializableAttribute public class MainMIDlet extends UiApplication {}

    public MainMIDlet() {}
    MainForm mf = new MainForm();
    pushScreen (mf);
    }

    Public Shared Sub main (String [] args) {}
    MainMIDlet mm = new MainMIDlet();
    mm.enterEventDispatcher ();
    }
    }

    Class MainForm

    import java.io.ByteArrayOutputStream.
    import java.io.IOException;
    import java.io.InputStream;

    Import javax.microedition.io.Connector;
    Import javax.microedition.io.HttpConnection;

    Import org.json.me.JSONArray;
    Import org.json.me.JSONObject;

    Import net.rim.device.api.system.EncodedImage;
    Import net.rim.device.api.ui.component.BitmapField;
    Import net.rim.device.api.ui.component.LabelField;
    Import net.rim.device.api.ui.container.MainScreen;

    SerializableAttribute public class MainForm extends form {}

    private String url = "http://user-xxx/json.js";
    private String [] jsonTitles = new String [5];
    private String [] jsonImages = new String [5];
    private LabelField lf = null;
    private BitmapField bf = null;

    public MainForm() {}

    try {}
    getJSON (url);
    } catch (IOException e) {}
    e.printStackTrace ();
    }

    LF = getLabelField(this.jsonTitles[0]);
    Add (LF);

    try {}
    BF = getBitmapField(this.jsonImages[0]);
    } catch (Exception e) {}
    e.printStackTrace ();
    }
    Add (BF);

    }

    Public Sub getJSON (String url) throws IOException {}
    StringBuffer sb = new StringBuffer();
    InputStream is = null;
    HttpConnection hc = null;
    try {}
    long bytesLength = 0;
    int ch = 0;
    HC = (HttpConnection), Connector.open (url);
    is = hc.openInputStream ();
    bytesLength = hc.getLength ();
    If (bytesLength! = - 1) {}
    for (int i = 0; i)< byteslength;="" i++)="">
    If ((ch = is.read (())! = - 1) {}
    SB. Append ((Char) ch);
    }
    }
    } else {}
    While ((ch = is.read (())! = - 1) {}
    bytesLength = is.available ();
    SB. Append ((Char) ch);
    }
    }
    parseJSON (sb.toString ());
    } {Finally
    is. Close();
    HC. Close();
    }
    }

    {} public void parseJSON (String sb)
    try {}
    JSONObject jo = new JSONObject (sb);
    If (jo! = null) {}
    JSONObject channel = jo.getJSONObject ("channel");
    If (channel! = null) {}
    JSONArray points = channel.getJSONArray("item");
    If (items! = null) {}
    for (int i = 0; i)< items.length();="" i++)="">
    JSONObject point = items.getJSONObject (i);
    this.jsonTitles [i] = item.getString ("title");
    this.jsonImages [i] = item.getString ("image");
    }
    }
    }
    }
    } catch (Exception e) {}
    e.printStackTrace ();
    }
    }

    public getLabelField (String title) {} LabelField
    LabelField lf = new LabelField (title);
    return of lf;
    }

    public BitmapField getBitmapField (String url) throws IOException {}
    InputStream is = Connector.openInputStream (url) (InputStream);
    BitmapField bf = null;
    try {}
    ByteArrayOutputStream Baos = new ByteArrayOutputStream();
    int ch;
    While ((ch = is.read (())! = - 1) {}
    Baos.Write (ch);
    }
    imageData Byte = baos.toByteArray ();
    BF = new BitmapField (EncodedImage.createEncodedImage (imageData, 0,))
    (imageData.length) .getBitmap ());
    } {Finally
    If (is! = null) {}
    is. Close();
    }
    }
    return (bf == null? null: bf);
    }

    }

  • Set the reference point for several objects in the middle of the document

    Hello community,

    I want to mirror a layout.

    I: Yes

    1. Select all objekts

    2. set the benchmark in the Middle

    3. objects in mirror

    BUT

    The reference point is in the middle of all the OBJECTS. This led to several objects across the border into my document because the layout is not spread out on a regular basis.

    I want through the DOCUMENT will be the point of reference. How can I do?

    Thank you

    Christian

    Have you fiugured this out yourself?

    I just played a little and found a method, but it is not really intuitive. Select the object, then go to the rotation tool. The center of rotation must be defined as one of the handles of transformation, but you can drag it anywhere you like, then move until you want as the center of your mirror. Hold down the Opt/Alt key and click on the button to create a mirrored copy. The objects original reflects their position around the reference repositioned without the modifier key.

  • Reference to the actual object during extraction to the cache coherence in C++

    Hello
    Currently I use the copy constructor to get the real object reference. But because of that when whenever for some call wire get object creates a new object in the heap. Because I have a few times I keep this object in the local cache. Is there a way that we can avoid creating new objects in the heap.

    void * get_for_read_write_lock (const char * key) {}
    String::view objectKey = key;
    lock_locally (objectKey, "get");
    Managed < cache_obj >: view obj = cast < < cache_obj > Managed: View > (hCache-> get (objectKey));
    If (obj == NULL) {}
    COH_LOG2 ("get object NULL with key lock:", objectKey);
    unlock_locally (objectKey, "get");
    return null;
    }
    cache_obj valueOb = new cache_obj(*obj); *
    unlock_locally (objectKey, "get");
    valueOb-> set_cache (Thi, key);
    Return valueOb;
    }

    Kind regards
    Sura

    Hi Sura,

    Can you please specify if you want a mutable or immutable object. As you can with a thread earlier, out-of-process consistency puts cached objects return mutable objects immutable return hide in the process. The in-process caches back those unchangeable to prevent changing the return value to appear as if they were made in the cache.

    The boxing_map will return mutable objects, although they use your copy constructor to produce so there is really no performance advantage to use it. A final version is returned it is only because force us the call to the constructor of copy of you restore an unmanaged version.

    Mark

    The Oracle coherence

  • How to make reference to a function object in a conditional statement?

    I currently have a conditional which looks like this:

    {if(!closeFunction)}
    this.removeEventListener (CloseEvent.CLOSE, closePopUp);
    }

    closeFunction is a: type of function and it works correctly, but I have this error warning?


    3553: function value used when the Object type is expected.  Maybe the parentheses () are missing after this function reference.

    Is there a better way to check if this feature is enabled or not?

    Try

    If (closeFunction is nothing)

    Gordon Smith

    Adobe Flex SDK team

  • How to make reference to the cantainer object

    Is there a way to refer to the object and other assets based on the position of the target

    var movies:Array = new Array({btn:btn_1,url:"cico.swf"},{btn:btn_2,url:"ianEastwood.swf"});
    
    for (var g:Number = 0; g< btns.length; g++) {
         movies[g].btn.addEventListener(MouseEvent.CLICK, menuClick);
    }
    
    function menuClick(evt:MouseEvent):void {
      eg.      trace(  (evt.target).container Object()    );
         
         
      eg.     trace(    ( (evt.target).cantainer  Object() ).url   );
    
    
    
    Ultimately this is what i want
    var ind:Number = movies.indexOf(the object in the array);
    trace (ind); // should be a number 
    
    
    
    }
    
    
    

    No object btn consists in movies.  It contains objects that contain objects btn.

    use:

    function menuClick(evt:MouseEvent):void {}

    for (var i: uint = 0; i<>

    {if (movies [i]. BTN is evt.currentTarget)}

    trace (i);

    breaking

    }

    }

    }

  • savedThis reference back to raise objections of timeline actionscript?

    I have a symbol exported from an external library. I have an instance of that symbol in the main application, put on the list display and subsequently detached from the display list. However, the instance does not disappear, it always crashes.

    The reason why I know that the Forum is still there is there a looping sound integrated in his chronology; the sound never stops playing.

    The reference object profiling reveals that there are 2 references to the instance, and both are functions of "savedThis" that appear to come from code embedded in the instance itself. See attachment of code.

    frame61 and frame17 contain actionscript (just a "stop()" ""). You can see these are executives of the actual instance, because the IDS match.

    Is there a way to get rid of these references to this object disappear? Really, it is simply referred to himself here. It seems that it should be garbage collector, but it's not.

    GC in version 9.0.124.0 player is defective. your best bet is to stop the sound prior to the removal of all referenced to the loaded object.

  • Attempting to reference a dynamically named object

    Hello. I'm doing an interactive game of cards and made primarily ( http://cards.positivedesign.co.uk ) but I'm having a slight problem. If you click on the link above, you'll see a bunch of right, click on the stack and the top card rises and returns to the Center. Click again on the stack on the right and the charge sheet down to a pile on the left and the next card back to the Center and so on. The problem occurs when you click the battery on the right the 3rd time, the charge sheet falls to the left, but goes UNDER the battery rather than above it.

    I don't know WHY its done this - I'm using the index of the child of the cards to choose which cards to return, so if you click on a map to the right and there's a hint of 5, it moves the map with index 6 from the Center to the left, etc - I don't know any other way to do. I tried to name the cards by a number, then the card bears the name of '1', and then I used a variable currentCard to follow what cards I should be mobile. However it would not work when I tried to select who are opposed to the tween, because I was referencing 'cardLayer.currentCard' instead of saying, 'cardLayer.card1 '...

    Hope that all of the senses. I would be grateful all the suggestions on where I'm wrong, or a better way to do?

    Yes, but changing the order objects on stage, as I said bringing that a card upwards, I then could not use the index of the child to work on what cards to use.

    I found another way of referencing the objects just fine... when I create cards in a loop for example, I put the objects themselves in a table and then reference them by their index in the table when I want to manipulate them.

    Thanks anyway!

Maybe you are looking for

  • What about datareporting.sessions.current.activeTicks in: config

    I wonder what that what follows about: config entries are for -datareporting.sessions.current.activeTicks (count in increments unique all few seconds) -datareporting.sessions.current.totalTime (in thousands jumping every few seconds) -datareporting.s

  • My special email cannot open

    Why my email cannot connect to the server?

  • the powerful 6008, measure a photodiode

    Hello I went through the forum and support pages for different 6008 questions, but I have a few questions. Especially how to choose between completed measurement or differential unique. I want to acquire the value DC of a photodiode amplified. http:/

  • HP's TouchSmart with Vista - need to upgrade, but not sure it?

    Hello! My husband gave me the touchsmart and didn't know that Vista wasn't good for my software that I use. I need to upgrade to 7, but not sure we should I get or if it will affect on the touch screen. can someone help me please? I think its a prett

  • Vista Home Basic Imaging

    My school has 20 Vista Home Basic Dell computers.  We have used for about a year and would now have a standard installation, config and the office.  Can I use a product like Acronis, Ghost, fog, or Clonzilla to get a standard image for these computer