必须捕获或声明要抛出未报告的异常java.io.ioexception

时间:2014-01-14 15:59:09

标签: java compiler-errors

这个编译错误意味着什么,我该如何解决? 编译器在第86行指出错误

final PiFace piface = new PiFaceDevice(PiFace.DEFAULT_ADDRESS, Spi.CHANNEL_0);

告诉我

unreported exception java.io.ioexception must be caught or declared to be thrown

它需要try / catch吗?因为这是我在搜索中找到的最佳答案,但是我不确定如何实现它我已经完成了它只会产生更多错误(你可以看到它被注释掉了)。

完整的代码如下:

public class Relay1 extends javax.swing.JFrame {

    public Relay1() {
        initComponents();
    }

    private void initComponents() {
        // stuff that doesn't matter...
    }


    //try{
        final PiFace piface = new PiFaceDevice(PiFace.DEFAULT_ADDRESS, Spi.CHANNEL_0);
    //}catch(IOException e){
        //System.out.println("Something went wrong...");
    //}


    public static void main(String args[]) throws InterruptedException, IOException {        
        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(Relay1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Relay1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Relay1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Relay1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Relay1().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    // End of variables declaration//GEN-END:variables
}

2 个答案:

答案 0 :(得分:3)

您确实没有为已检查的例外提供任何处理代码。如果该异常只传播给调用者,在这种情况下写入new Relay1()的位置,那将是完全可以接受的。为此,请写如下:

final PiFace piface; { 
  try {
    piface = new PiFaceDevice(PiFace.DEFAULT_ADDRESS, Spi.CHANNEL_0);
  } catch(IOException e) { 
    throw new RuntimeException("Failed to create Pi Face Device", e); 
  }
}

这将允许您在异常中保留诊断信息,并满足编译器的期望。

答案 1 :(得分:0)

在try块之前声明你的PIFace,然后用try{ }包围它的初始化,然后在它之后放一个catch块来处理异常。如果你只是用try块包围它,而没有先初始化它,那么变量的范围将仅限于该块。所以做一些像:

PiFace piface;
try{
   piface = new PiFaceDevice(PiFace.DEFAULT_ADDRESS, Spi.CHANNEL_0);
   }
   {catch(Exception e) {
      e.printStackTrace();
   }