Nathan
Nathan

Reputation: 1347

Throw exception at class level

In my class, I have a method that utilises the awt.Robot class, and I instantiate Robot() every time I run this method. I think this is slowing my processing down significantly though because in cases where the method is run 10000 times in a loop, I'm instantiating Robot() 10000 times instead of just once. If I can declare it as a global, that would solve my problems. I attempted:

Robot robot = new Robot();

Just under my class, but I need to throw the exception to use that line. Unfortuately I don't know how to do this without a try/catch block which I can't do outside of a method.

How can I get around this and initialize robot as a global?

Upvotes: 0

Views: 1039

Answers (2)

Sparkst3r
Sparkst3r

Reputation: 23

Can you do this?

So long as you only have one of these classes, see singleton pattern. There will only be one Robot, making all calls to "yourRobotUsingMethod" use only one Robot.

By initializing your robot class in your class constructor, you can try/catch the initialization as the class is instatiated.

class YourClass {

    private Robot robot;    

    public YourClass() { 

        try {
            robot = new Robot();
        }
        catch(Exception e) {
            //Catch your exception here
        }
    }

    public void yourRobotUsingMethod() {
        //Use your robot here
        //You might want to check if robot is not null here too.
    }
}

I'm sorry if I've messed the keywords up, I've gotten used to C++'s block access levels. But you should get the idea

Upvotes: 1

LhasaDad
LhasaDad

Reputation: 2143

You could put the instantiation in a static block

 static Robot robot;
 static {
    try {
       robot = new Robot();
    catch()
    {}
    }

Upvotes: 1

Related Questions