try-catch不会捕获IOException

时间:2012-11-13 21:05:20

标签: java try-catch ioexception

在以下代码中,我得到了Unreachable catch block for IOExceptionIOException } catch (IOException e){class driver { public static void main(String[] args) { // TODO Auto-generated method stub Customer forrest = new Customer("Forrest Gump", 1, "42 New Street, New York, New York"); Customer random = new Customer("Random Name", 2, "44 New Street, New York, New York"); Customer customer[] = { null, forrest, random }; int whichOption = 1; int id = 0; char action = ' '; char accSrc = ' '; char accDest = ' '; double amount = 0; BankAccount src = null; do { try{ // process JOptionPane input information String input = JOptionPane .showInputDialog("Please enter your transaction information: "); Scanner s = new Scanner(input); id = Integer.parseInt(s.next()); action = Character.toUpperCase((s.next().charAt(0))); if (action == 'T') { amount = s.nextDouble(); accSrc = s.next().charAt(0); accDest = s.next().charAt(0); } else if (action == 'G' || action == 'I') { accSrc = s.next().charAt(0); } else { // if D,W amount = s.nextDouble(); accSrc = s.next().charAt(0); } } catch (IOException e){ } // taking action accordingly (T)ransfer, (D)eposit, (W)ithdraw, (I)nterest if (action == 'T') { (customer[id].getAccount(accSrc)).transfer(amount, customer[id].getAccount(accDest)); } else if (action == 'G') { System.out.println("The current balance on your " + accSrc + " account is " + customer[id].getAccount(accSrc).getBalance() + "\n"); } else if (action == 'D') { (customer[id].getAccount(accSrc)).deposit(amount); } else if (action == 'W') { (customer[id].getAccount(accSrc)).withdraw(amount); } else if (action == 'I') { (customer[id].getAccount(accSrc)).computeInterest(); } whichOption = JOptionPane .showConfirmDialog(null , "Do you want to continue?"); System.out.println("The balance on " + customer[id].getName() + " auto account is " + customer[id].A.balance); System.out.println("The balance on " + customer[id].getName() + " savings account is " + customer[id].S.balance); System.out.println("The balance on " + customer[id].getName() + " checkings account is " + customer[id].C.balance); System.out.println("The balance on " + customer[id].getName() + " loan account is " + customer[id].L.balance + "\n"); } while (whichOption == 0); } } 的问题声明正文错误(带下划线)永远不会抛出此异常吗?

{{1}}

6 个答案:

答案 0 :(得分:11)

这是因为您在try/catch内执行的任何操作都不会抛出IOException。

根据扫描程序javadoc

大多数Scanner类方法都抛出FileNotFoundException(这不适用于您的情况,因为没有从文件中读取)(或)IllegalArgumentException(或)IllegalStateException

您需要将IOException更改为上述任一异常(或)删除try / catch。

答案 1 :(得分:4)

您可以删除IOException和try catch,因为try catch中的所有语句都没有抛出此异常

答案 2 :(得分:3)

好像你在try区块正在抛出IOException

答案 3 :(得分:3)

该try块中没有方法调用抛出IOException,这就是catch是无法访问的代码的原因。

您可以安全地删除try和catch,因为这种情况永远不会发生。

答案 4 :(得分:3)

您的catch块为空,表示您无论如何都不会真正处理异常。你可能在那里有一些代码让你抓住它,但现在你已经没有它了。只需移除整个周围try-catch,就不会有其他问题。

答案 5 :(得分:1)

try/catch块为空,代码不是抛出IOException,但它可能抛出其他异常。