gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:49:37 28 4
gpt4 key购买 nike

这个编译错误是什么意思,我该如何解决?编译器将错误指向第 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
}

最佳答案

您确实没有任何处理代码可以为您检查的异常提供。如果该异常只传播到调用者,这是完全可以接受的,在本例中是写入 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);
}
}

这将使您既可以在异常中保留诊断信息,又可以满足编译器的要求。

关于java - 未报告的异常 java.io.ioexception 必须被捕获或声明为抛出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21117967/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com