Search code examples
javacompiler-errorsawtawtrobot

Robot Class - Unhandled exception type AWTException


So, I was was tinkering around with the Robot Class in Java. I am a very new Java Programmer, but I have deeper roots in other languages. Here's my code:

import java.awt.*;

public class Main {

    public static void main(String[] args) {
        Robot bot = new Robot();
        bot.mouseMove(50, 50);  
    }
}

All I was trying to do was see if I can control the mouse, as in, moving it to 50, 50. However, in Eclipse it puts a red X next to

Robot bot = new Robot();

..saying..

Unhandled exception type AWTException

And won't let me run it. Can anyone help me figure out why this is happening?


Solution

  • you need to try/catch exceptions:

    import java.awt.*;
    public class Main{
    
    public static void main(String[] args) {
    
        try
        {
        Robot bot = new Robot();
        bot.mouseMove(50, 50);  
        }
        catch (AWTException e)
        {
        e.printStackTrace();
        }
    }
    }
    

    or throw the exception:

    import java.awt.*;
    public class Main throws AWTException{
    
    public static void main(String[] args) {
        Robot bot = new Robot();
        bot.mouseMove(50, 50);  
    }
    }