Try&中的语法错误捕获

时间:2016-11-24 08:11:38

标签: java syntax try-catch token

我在完成Try and Catch时遇到问题。我一直收到一个语法错误,要求提供“(”“{”“;”不需要它们的标记。搜索到所有的答案,我还没有得出结论,为什么我一直收到这个错误。这里是我的代码

import javax.swing.JOptionPane;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.MenuBar;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebHistory;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

public class Browser extends Application{

final Button Back = new Button("<-");
final Button Forward = new Button ("->");
final Button Home = new Button("Home");
final Button Reload = new Button("r");
final MenuBar menuBar = new MenuBar();
final TextField txt = new TextField();

@Override
public void start(Stage stage) throws Exception{
    VBox hBox = new VBox();
    WebView wv = new WebView();
    WebEngine engine = wv.getEngine();
    WebHistory wh = engine.getHistory();
    engine.load("https://www.google.com");

    txt.setOnAction(new EventHandler<ActionEvent>(){
        try{
            public void handle(ActionEvent event){
                engine.load(txt.getText());
            }
        }catch(Exception e){
            showError("Unable to load site");
        }
    });
    hBox.getChildren().setAll(txt, wv);

    Scene scene = new Scene(hBox, 800, 600);
    stage.setTitle("Anthony Gayflor-CS260 OOP");
    stage.setScene(scene);
    stage.show();

}

private void showError(String errorMessage){
    JOptionPane.showMessageDialog(this, errorMessage, "Error", JOptionPane.ERROR_MESSAGE);
}

public static void main(String[] args){
    Application.launch(args);
}
}

当我编译它时,我得到的错误是

Caused by: java.lang.Error: Unresolved compilation problems: 
Syntax error, insert "}" to complete ClassBody
Syntax error, insert ")" to complete MethodInvocation
Syntax error, insert ";" to complete Statement
Syntax error on token "(", ; expected
Syntax error on token ")", ; expected
Syntax error on tokens, delete these tokens

at Browser.start(Browser.java:33)

3 个答案:

答案 0 :(得分:0)

try-catch块必须在方法内:

 public void handle(ActionEvent event){
    try{
            engine.load(txt.getText());
    }catch(Exception e){
           showError("Unable to load site");
    }
 }

答案 1 :(得分:0)

除了Jens的回答,你可以在Java 8中使用lambda,因为txt.setOnAction(event -> { try { engine.load(txt.getText()); }catch (Exception e) { showError("Unable to load site"); } }); 是一个功能接口。然后您的代码将如下所示:

vm.memory.size[pused]

答案 2 :(得分:0)

您不能在try / catch子句中定义方法!!!

将try / catch子句放入方法中。