Try and Catch method

I use a try and catch method to see if the string input was a valid integer or not (I try to parse it then catch a number exception if there is one). However the new integer i create from the string (if theres no exception) doesn't seem to initialize after i close the Try method. How can I create this variable so it's scope is seen by the entire program.

Try{
int = Double.parseDouble(stringInput);
}catch (NumberFormatException nFE){
system.out.println("Try again");
}

System.out.println(int);//Variable might have not been initialized (error)

Comments

  • : I use a try and catch method to see if the string input was a valid integer or not (I try to parse it then catch a number exception if there is one). However the new integer i create from the string (if theres no exception) doesn't seem to initialize after i close the Try method. How can I create this variable so it's scope is seen by the entire program.
    :
    : Try{
    : int = Double.parseDouble(stringInput);
    : }catch (NumberFormatException nFE){
    : system.out.println("Try again");
    : }
    :
    : System.out.println(int);//Variable might have not been initialized (error)
    :
    :
    You should either initialize the value to a default value before the try-catch block, or within the catch block. If an exception occurs, the variable int isn't initialized, which causes the error.
  • I have it looped so that if a valid integer isn't entered they have to keep trying. It's only when i try and express the variable outside of the block it gives me an error. But if i express the variable inside the block it prints to screen (the program compiles).
  • : I have it looped so that if a valid integer isn't entered they have to keep trying. It's only when i try and express the variable outside of the block it gives me an error. But if i express the variable inside the block it prints to screen (the program compiles).
    :
    The compiler cannot evaluate how often a loop runs. Thus the code:
    [code]
    while
    {
    try
    int = something
    catch () {
    }
    }
    read int
    [/code]
    will be evaluated by the compiler in every way. This will give an execution-path, for which int has not been initialized (an error and only 1 time through the loop). Even if the loop cannot exit without int having a value, the compiler still takes that possibility into account.
    The solution is simple:
    [code]
    int = 0; // give int a default value
    while
    {
    try
    int = something
    catch () {
    }
    }
    read int
    [/code]
    If the loop is well designed, int will never be 0, unless something equals 0.
  • thanks, works fine now....funny how you can easily forget the simple things.
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories