Java – 必须抛出异常,但如何?
发布时间:2020-12-15 02:03:28 所属栏目:Java 来源:网络整理
导读:我在NetBeans中收到错误,说我必须在此方法中抛出SQLException: private void displayCustomerInfo(java.awt.event.ActionEvent evt) { int custID = Integer.parseInt(customerID.getText()); String info = getCustomerInfo(custID); results.setText(info
我在NetBeans中收到错误,说我必须在此方法中抛出SQLException:
private void displayCustomerInfo(java.awt.event.ActionEvent evt) { int custID = Integer.parseInt(customerID.getText()); String info = getCustomerInfo(custID); results.setText(info); } 此方法由NetBeans创建,因此不允许我编辑签名并抛出异常.这就是我创建getCustomerInfo()方法的原因.此方法会抛出异常,因为它使用一种方法从数据库中检索有关客户的信息. public String getCustomerInfo(int cid) throws SQLException { Customer c = proc.getCustomer(cid); // get info return "info"; } getCustomer方法也抛出异常并且proc.java编译. 确切的错误是 unreported exception java.sql.SQLException; must be caught or declared to be thrown 解决方法
通常,如果您的代码需要抛出签名不支持的Exception类型,并且您无法控制接口,则可以捕获并重新抛出接口支持的类型.如果您的接口未声明任何已检查的异常,则始终可以抛出RuntimeException:
private void displayCustomerInfo(java.awt.event.ActionEven evt) { try { int custID = Integer.parseInt(customerID.getText()); String info = getCustomerInfo(custID); results.setText(info); } catch (SQLException ex) { throw new RuntimeException(ex); // maybe create a new exception type? } } 您几乎肯定想要创建一个扩展RuntimeException的新Exception类型,并让您的客户端代码捕获该异常.否则,您将冒着捕获任何RuntimeException的风险,包括您的客户端代码可能无法处理的NullPointerException,ArrayIndexOutOfBoundsException等. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |