2015-07-22 47 views
1

經過一番快速調查,我找不到任何東西,部分原因是我不確定我是否正在尋找正確的東西,部分是因爲我不認爲它存在。有沒有一種方法可以壓縮Java Try Catch Blocks?

但是讓我知道是否有辦法我可以壓縮這個。另外我是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); 
    } 
}); 

回答

11

您可以使用多捕捉(分鐘JDK 7): 只需使用|標誌單獨的異常類

try { 
    someMethod(); 
} catch (IOException | SQLException e) { 
    e.printStackTrace(); 
} 
+0

您還可以捕獲所有這些異常的共同父項,即catch(Exception e)'。但要小心使用它,因爲它也會捕捉你可能不想要的東西。 – Codebender

1

因爲這似乎並沒有成爲一個嚴重錯誤(你的程序可能會繼續) - 也許你可以捕獲你的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); 
} 
相關問題