处理Java异常
我不明白为什么我的代码编译不正确。。我可以检查代码,直到到达catch块。它工作,显示消息,所以我知道它正在捕获错误。然而,在我的程序结束时,它说我在同一个地方有同样的错误。我看不出我做错了什么。谢谢你的帮助处理Java异常,java,exception,Java,Exception,我不明白为什么我的代码编译不正确。。我可以检查代码,直到到达catch块。它工作,显示消息,所以我知道它正在捕获错误。然而,在我的程序结束时,它说我在同一个地方有同样的错误。我看不出我做错了什么。谢谢你的帮助 class Verification { String detAccess(String[] pL, String[] uL, String pass, String user) { int pos = 0; String access = ""; try {
class Verification {
String detAccess(String[] pL, String[] uL, String pass, String user) {
int pos = 0;
String access = "";
try {
for (int i=0; !user.equals(uL[i]); i++)
pos++;
} catch (ArrayIndexOutOfBoundsException exec) {
System.out.println("Username doesn't exist.");
throw exec;
}
if(pass.equals(pL[pos])) {
access = "MEMBER";
} else {
System.out.println("Incorrect password.");
access = "DENIED";
}
return access;
}
}您正在重新引发异常-
抛出exec
您正在重新抛出异常。处理异常的要点是它不能继续进行。有两个问题:
throw exec;
您成功捕获了异常,但随后再次抛出。如果没有其他内容捕获它,程序将在错误中终止。您正在重新引发异常 还有一件事:
if(pass.equals(pL[pos])) {
access = "MEMBER";
这将导致异常再次出现,即使您没有重新显示它,因为它将尝试使用不存在的索引检查密码列表。您应该将代码重写为以下内容:
int pos = -1;
...
for (int i=0;uL.length; i++)
{
if(user.equals(uL[i])) { pos=i; break; }
}
...
if(pos==-1)
{
// user not found
} else {
// test the pass with pos as index
}
你又犯了同样的错误。谁在您原来的“catch”块之外捕获它?这不是代码中的唯一问题,至少在
pL
和uL
长度相同的情况下。啊哈!!非常感谢。这修复了它,我甚至不必使用试接块。再次感谢!!:)