java - Try & Catch 中的语法错误

标签 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)

最佳答案

除了 Jens 的回答之外,您还可以在 Java 8 中使用 lambda,因为 EventHandler 是一个函数式接口(interface)。那么你的代码将如下所示:

txt.setOnAction(event -> {
    try {
        engine.load(txt.getText());
    }catch (Exception e) {
        showError("Unable to load site");
    }
});

关于java - Try & Catch 中的语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40781014/

相关文章:

JavaCV:如何获取描述符的二进制字符串

Perl::访问具有 `use strict` 集的对象的成员?

java - Java读写文件和添加行号

javascript - 在 JavaScript/Nodejs 中动态处理 undefined variable 的最佳实践

java - 堆栈、括号匹配

具有更多数据结构的 Java 库

java - 从 LinkedHashMap 中输入的键获取特定的下界值

c# - 与子类型名称同名的属性

powershell - PowerShell 是否要求脚本 block 的左花括号在同一行上?

javascript - 在函数中拒绝不返回错误