有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

有没有一种压缩Java Try-Catch块的方法?

在做了一些快速的研究之后,我找不到任何东西,部分原因是我不确定我是否在寻找正确的东西,部分原因是我认为没有

不过,请让我知道是否有一种方法可以浓缩这一点。我也是Java新手,如果你能用简单的术语解释一下你的变化和它的作用,那也太好了

try {
    for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager
            .getInstalledLookAndFeels()) {
        if ("Nimbus".equals(info.getName())) {
            javax.swing.UIManager.setLookAndFeel(info.getClassName());
            break;
        }
    }
} catch (ClassNotFoundException ex) {
    java.util.logging.Logger.getLogger(GameOfLife.class.getName()).log(
            java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
    java.util.logging.Logger.getLogger(GameOfLife.class.getName()).log(
            java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
    java.util.logging.Logger.getLogger(GameOfLife.class.getName()).log(
            java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
    java.util.logging.Logger.getLogger(GameOfLife.class.getName()).log(
            java.util.logging.Level.SEVERE, null, ex);
}

java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
        new GameOfLife().setVisible(true);
    }
});

共 (2) 个答案

  1. # 1 楼答案

    您可以使用Multi-Catch(minjdk 7): 只需使用|符号来分隔异常类

    try {
        someMethod();
    } catch (IOException | SQLException e) {
        e.printStackTrace();
    }
    
  2. # 2 楼答案

    因为这似乎不是一个严重错误(您的程序可能会继续),所以您可以捕获catch块中的所有异常。比如:

    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager
            .getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (Exception ex) {
        java.util.logging.Logger.getLogger(GameOfLife.class.getName()).log(
            java.util.logging.Level.SEVERE, null, ex);
    }