Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用抛出时出现编译器错误_Java - Fatal编程技术网

Java 使用抛出时出现编译器错误

Java 使用抛出时出现编译器错误,java,Java,下面是我在这个网站上找到的一个简单示例,我有示例代码 import java.awt.*; public class Main throws AWTException{ public static void main(String[] args) { Robot bot = new Robot(); bot.mouseMove(50, 50); } } 当我编译这个时,我得到了错误 Main.java:2: error: '{' expected public class

下面是我在这个网站上找到的一个简单示例,我有示例代码

import java.awt.*;
public class Main throws AWTException{

public static void main(String[] args) {
    Robot bot = new Robot();
    bot.mouseMove(50, 50);  
}
}
当我编译这个时,我得到了错误

Main.java:2: error: '{' expected
public class Main throws AWTException {
                 ^
1 error

有人能解释一下怎么回事吗?我尝试了许多不同的方法,对我来说,似乎编译器根本无法识别“throws”这个词

不能在类级别抛出异常,可以在方法级别抛出异常,如下所示:

1)
throw
在方法体中,尝试catch块包装可能引发异常的特定语句

    public class Test{
        public Test(){

        }

        public void testMethod(){
            try{
                //statements might throw exception
            }catch(Exception e){
                //must print the exception message here, it's a good habit...
            }
        }
    }
2)
在方法声明中抛出
,它将异常传播到调用
testMethod()
的方法,这对进一步跟踪异常非常有帮助

    public class Test{
        public Test(){

        }

        public void testMethod() throws Exception{
            //code goes here
        }
    }
3)
在类构造函数声明中抛出

public class Test{
    public Test() throws Exception{

    }
}
就你而言:

import java.awt.*;
public class Main {

    public static void main(String[] args)throws AWTException {
        Robot bot = new Robot();
        bot.mouseMove(50, 50);  
    }
}
或者在静态main方法中:

public static void main(String[] args){
    Robot bot = new Robot(); // if Robot constructor declared AWTException
                             // the class instance initialization line should
                             // be wrapped in the try-catch block as well
    try{
        bot.mouseMove(50, 50);//mouseMove might throw AWTException
    }catch( AWTException awte){
        System.err.println("Exception thrown:" + awte.getMessage());
    }
}

非常感谢。奇怪的是,这个网站上给出的示例代码被多次升级。如果您能给出一个代码片段,正确地创建一个可以在try语句之外使用的Robot,我将万分感激。第二种方法不起作用。我是java新手,所以我不确定这是否取决于您使用的系统/编译器。只有当bot声明在try语句中时,它才起作用。@user3799584我没有自己测试它,只是指出了一种解决方法,您可以将这两行都包装到try-catch语句中,然后它将与方法声明后的
抛出AWTException
相同。@user3799584这可能是因为Robot构造函数声明了类似
公共Robot抛出AWTException{…}