Results 1 to 15 of 15
  1. #1
    docesam is offline Member
    Join Date
    Apr 2009
    Posts
    14
    Rep Power
    0

    Default What to do about it : "Try" makes object instances out of scope

    Consider this simple program:

    Java Code:
    package com.arabguru;
    
    import sun.text.normalizer.UTF16;
    
    import java.io.IOException;
    import java.nio.file.Paths;
    import java.util.Scanner;
    
    public class Main {
    
        public static void main(String[] args) {
            // write your code here
            try
            {
                Scanner sc1 = new Scanner(Paths.get("C:\\file1.txt"), "UTF8");
            }
            catch (IOException e)
            {
                // do stuff in response
                e.printStackTrace();
            }
    
            try
            {
                Scanner sc2 = new Scanner(Paths.get("C:\\file2.txt"), "UTF8");
            }
            catch (IOException e)
            {
                // do stuff in response
                e.printStackTrace();
            }
    
            while (sc1.hasNext() && sc2.hasNext())
            {
                String temp = sc1.nextLine();
                System.out.println(temp);
                temp = sc2.nextLine();
                System.out.println(temp);
            }
        }
    }
    the first try block create a scanner object for the first file ,the second try do the same for the second file. i am wrapping each one of those in its own try because i want to deal with an exception in each one differently. but when i come to the while block sc1 and sc2 is out of scope .i tried declaring scanner objects (but not initializing them) before the try block but the compiler complain ( variable sc1 might not have been initialized).
    how can wrap each scanner creation operation in its own try catch and still keep them in scope ?

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,003
    Rep Power
    33

    Default Re: What to do about it : "Try" makes object instances out of scope

    Define the variables outside of the try, initialize them with null and assign them values inside of the try statements.
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    26

    Default Re: What to do about it : "Try" makes object instances out of scope

    Or put it all (Scanner creation and your while loop) in a single try/catch.
    There's no point continuing processing if one of your Scanners fails to load.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  4. #4
    docesam is offline Member
    Join Date
    Apr 2009
    Posts
    14
    Rep Power
    0

    Default Re: What to do about it : "Try" makes object instances out of scope

    Quote Originally Posted by Norm View Post
    Define the variables outside of the try, initialize them with null and assign them values inside of the try statements.
    in this example it works ,but what if the type is not nullable ?

  5. #5
    docesam is offline Member
    Join Date
    Apr 2009
    Posts
    14
    Rep Power
    0

    Default Re: What to do about it : "Try" makes object instances out of scope

    Quote Originally Posted by Tolls View Post
    Or put it all (Scanner creation and your while loop) in a single try/catch.
    There's no point continuing processing if one of your Scanners fails to load.
    i agree that there is no point to continue if one of the scanners fails. however i want each one of the scanner to be wrapped in it's own try block because the exception handling is different. for example if the first scanner failed i would like to inform the user and that's it. but if the second scanner failed i would like to throw exception so that another file will be tried (for example).

  6. #6
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,003
    Rep Power
    33

    Default Re: What to do about it : "Try" makes object instances out of scope

    what if the type is not nullable
    All class variables can have a null value. primitives can be set to a default value
    If you don't understand my response, don't ignore it, ask a question.

  7. #7
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: What to do about it : "Try" makes object instances out of scope

    Why do you think the scanners would fail? If it is because the file is not there, then perhaps you should verify that first before attempting to
    open the file.

    But more to your problem. You could put everything in a single try statement. You could then use individual flags to determine where specific state
    in the try block was changed. You can use that state to handle the exceptions appropriately.

    But I have to admit that having suggested that, it sounds kludgy.

    Regards,
    Jim
    Last edited by jim829; 01-27-2016 at 04:22 PM.
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  8. #8
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    26

    Default Re: What to do about it : "Try" makes object instances out of scope

    Java Code:
    Scanner sc1 = getUserScanner("some file name"); // throws an Exception which will result in exiting
    Scanner sc2 = getSecondScanner();  // This method holds all the logic around asking for the file
                                        // and handling errors
    processScanners(sc1, sc2);
    In other words, don't do it all in one go, since you have logic you want to apply to each part.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  9. #9
    docesam is offline Member
    Join Date
    Apr 2009
    Posts
    14
    Rep Power
    0

    Default Re: What to do about it : "Try" makes object instances out of scope

    Quote Originally Posted by Norm View Post
    All class variables can have a null value. primitives can be set to a default value
    right, all reference types can have null reference value. that will be the solution then.
    Last edited by docesam; 01-27-2016 at 07:19 PM.

  10. #10
    docesam is offline Member
    Join Date
    Apr 2009
    Posts
    14
    Rep Power
    0

    Default Re: What to do about it : "Try" makes object instances out of scope

    Quote Originally Posted by jim829 View Post
    Why do you think the scanners would fail? If it is because the file is not there, then perhaps you should verify that first before attempting to
    open the file.

    But more to your problem. You could put everything in a single try statement. You could then use individual flags to determine where specific state
    in the try block was changed. You can use that state to handle the exceptions appropriately.

    But I have to admit that having suggested that, it sounds kludgy.

    Regards,
    Jim
    the scanner could fail due to permission issues.

  11. #11
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: What to do about it : "Try" makes object instances out of scope

    Then resolve this before invoking the scanner. Check out the File class. It contains methods for
    checking file access. You can also pass in instance of File to the Scanner constructor.


    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  12. #12
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    26

    Default Re: What to do about it : "Try" makes object instances out of scope

    And I would do all that in their own methods.
    These are separate tasks, so should be separate methods with rules about what they return.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  13. #13
    docesam is offline Member
    Join Date
    Apr 2009
    Posts
    14
    Rep Power
    0

    Default Re: What to do about it : "Try" makes object instances out of scope

    Quote Originally Posted by jim829 View Post
    Then resolve this before invoking the scanner. Check out the File class. It contains methods for
    checking file access. You can also pass in instance of File to the Scanner constructor.


    Regards,
    Jim
    good to know thank you.



    anyway , if the return value from the first try block is not nullable i don't know how to do that. for example:

    Java Code:
    try
      {
        int result1 = doSomething();  //can return any value positive or negative or zero
      }
      catch
      {
         // inform the user and quit this method
      }
    
    
      try
      {
        int result2 = doSomethingElse(); //can return any value positive or negative or zero
      }
      catch
      {
    
        //throw exception
      }
    
    
    
    return calculateSomething(result1,result2);
    in this case calculateSomething(result1,result2) will not be able to get result1 and result2 in scope because they are not nullable.

    my opinion is that contrary to all other block types ,the try block should not limit scope of objects declared inside it. because the try block should not be considered a "true block" it is rather a safeguard mechanism. but i am not oracle.

  14. #14
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    26

    Default Re: What to do about it : "Try" makes object instances out of scope

    Those methods should deal with the issues by throwing the relevant exception.

    Java Code:
    try {
        int res1 = doSomething1();
        int res2 = doSomething2();
        return calculateSomething(res1, res2);
    } catch (ExceptionFrom1 ex) {
        // do whatever for this exception
    } catch (ExceptionFrom2 ex) {
       // do whatever for this exception
    }
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  15. #15
    docesam is offline Member
    Join Date
    Apr 2009
    Posts
    14
    Rep Power
    0

    Default Re: What to do about it : "Try" makes object instances out of scope

    Quote Originally Posted by Tolls View Post
    Those methods should deal with the issues by throwing the relevant exception.

    Java Code:
    try {
        int res1 = doSomething1();
        int res2 = doSomething2();
        return calculateSomething(res1, res2);
    } catch (ExceptionFrom1 ex) {
        // do whatever for this exception
    } catch (ExceptionFrom2 ex) {
       // do whatever for this exception
    }
    thank you very much. that works

Similar Threads

  1. Replies: 10
    Last Post: 06-20-2015, 04:40 AM
  2. Replies: 0
    Last Post: 12-07-2012, 09:29 AM
  3. Replies: 3
    Last Post: 10-30-2012, 04:06 PM
  4. Replies: 4
    Last Post: 06-14-2011, 05:59 AM
  5. Replies: 1
    Last Post: 10-20-2008, 08:35 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •