Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

static class vairables and IOException

Status
Not open for further replies.

mackey333

Technical User
May 10, 2001
563
US
I am trying to declare static class variables which are filled with returns from file read methods:

public class myClass
{
public static int nBikeRides = OtherClass.getInt();
public static int nRuns = OtherClass.getInt();

public static void main(String args[]
{
....
}
}

However, it won't let me do this because I have to throw or catch the java.io.IOException. I cannot use a try and catch here, nor can I have the class throw the exception. Is there a way around this or do I have to set them to 0 and initialize from a method?

-Greg :-Q

flaga.gif
 
You will have to either throw or catch the exception. Can you elaborate on why neither will work in this case?

Have you considered catching and ignoring the exception in your static method? Purists around the world shudder to think about ignoring exceptions, but it is an option:

try {
FileWriter file = new FileWriter( "Output" );
} catch( IOException e ) {
// Ignored
}
 
You can catch (or ignore) the exceptions in a static initializer:

Code:
   public class myClass
   {
        public static int nBikeRides;
        public static int nRuns;
        static
        {
           try
           {
               nBikeRides = OtherClass.getInt();
               nRuns = OtherClass.getInt();
           }
           catch (Exception e)  
           {
              ...
           }
        }
                                 
        public static void main(String args[]
        {
            ....
         }
   }
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top