user5081555
user5081555

Reputation:

Is there a way to condense Java Try Catch Blocks?

After doing some quick research I couldn't find anything partly because I'm not sure if I'm searching the right thing and partly because I don't think there is.

However let me know if there is a way I could condense this. Also I'm new to Java and if you could explain your changes and what it does in simple terms that would be great too!

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);
    }
});

Upvotes: 1

Views: 273

Answers (2)

hinneLinks
hinneLinks

Reputation: 3736

You can use Multi-Catch (min JDK 7): Just use the | sign to seperate the Exception-Classes

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

Upvotes: 11

Dakshinamurthy Karra
Dakshinamurthy Karra

Reputation: 5463

Since this doesn't seem to be a critical error (your program may continue) - May be you can catch all exceptions in your catch block. Something like:

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);
}

Upvotes: 1

Related Questions