在下面的代码中我得到了
Unreachable catch block for IOException
。这个异常永远不会从 try
语句的主体中抛出,错误(下划线)与 IOException
中的 } 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);
}
}
这是因为您在
try/catch
中执行的任何操作都不会抛出 IOException。
根据扫描仪javadoc
大多数 Scanner 类方法都会抛出
FileNotFoundException
(这不适用于您的情况,因为不从文件中读取)(或)IllegalArgumentException
(或)IllegalStateException
您需要将
IOException
更改为上述任一异常(或)删除 try/catch。
您可以删除 IOException 和 try catch,因为 try catch 中的任何语句都不会抛出此异常
似乎您在
try
块中所做的任何事情都没有抛出 IOException
该 try 块中的方法调用不会抛出
IOException
,这就是为什么 catch 是无法访问的代码。
您可以安全地删除 try 和 catch,因为这种情况永远不会发生。
您的
catch
块是空的,表明您无论如何都不会真正处理异常。您可能有一些代码让您捕获它,但现在您不再拥有它了。只要把周围的整个try-catch
去掉就不会再有问题了
try/catch
块为空,代码不会抛出IOException
,但可能会抛出其他异常。