Search code examples
javaawtglobalawtrobot

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?


Solution

  • You could put the instantiation in a static block

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