简体   繁体   English

处理Java异常

[英]Handling a Java Exception

I can't figure out why my code isn't compiling correctly.. I can go through the code till it gets to the catch block. 我无法弄清楚为什么我的代码无法正确编译。.我可以遍历代码,直到到达catch块为止。 It works, displaying the message, so I know it's catching the error. 它可以正常工作,显示消息,所以我知道它正在捕获错误。 However, it ends my program saying I have that same error at the same place. 但是,它结束了我的程序,说我在同一位置有相同的错误。 I can't see what I am doing wrong. 我看不到我在做什么错。 Thanks for any help!! 谢谢你的帮助!!

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;        
}

} }

您要抛出异常的throw exec

You're rethrowing the exception. 您要抛出异常。

Another thing: 另一件事:

if(pass.equals(pL[pos])) {
    access = "MEMBER";

That will cause the exception to come up again even if you didn't rethrow it as it'll try to check the password list with a nonexistent index. 即使您没有重新抛出异常,这也会导致异常再次出现,因为它将尝试使用不存在的索引检查密码列表。

You should rewrite your code to something like this: 您应该将代码重写为以下形式:

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
}

you are throwing the exception back up. 您正在抛出异常备份。 the point of handling the exception is that it wron't carry on. 处理异常的关键是它不会继续进行。

Two problems: 两个问题:

  1. You're catching and rethrowing the exception; 您正在捕获并抛出异常; if you "handle it", you don't need to rethrow it. 如果您“处理”它,则无需将其扔掉。

  2. You're using "Exception Handling" to manage the "normal control flow" through your program. 您正在使用“异常处理”来管理程序中的“正常控制流”。 This is generally considered "bad style". 通常将其视为“不良样式”。 Can you not control your iteration, and determine that "you're done" by looking something else? 您是否可以控制迭代并通过查看其他内容来确定“您已完成”?

    UPDATE: ie nio's example 更新:即尼奥的例子

The code is compiling correctly if you're able to run it. 如果您能够运行,则代码可以正确编译。 As for the program ending in error, that's because you're throwing an exception: 至于以错误结尾的程序,那是因为您抛出了异常:

throw exec;

You successfully caught the exception, but then you threw it again. 您成功捕获了异常,但随后又将其抛出。 If nothing else catches it, the program will terminate in an error. 如果没有其他发现,程序将终止并显示错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM