java 具有相同异常类型的多个catch语句

ippsafx7  于 2023-08-01  发布在  Java
关注(0)|答案(3)|浏览(95)

我一直在寻找这个问题的答案,但还没有找到。
基本上,我试图通过GUI连接到数据库服务器。我的老板希望能够输入所有字段,然后检查它们是否是有效的条目,然后如果有任何无效的条目,他希望我将文本变为红色,表明该字段无效。我有try语句catch ClassNotFoundException和SQLException。因为有多个字段需要检查,所以我尝试使用一组if语句来检查连接信息。下面是代码,希望有意义...

//The cancel boolean values in this code are used elsewhere to regulate the Threads
    try 
    {
                   //attempt connection here
    } 
    catch(ClassNotFoundException | SQLException e)
    {
        String[] errors = new String[4]; //This will create a String array of the errors it catches
                                         //and will later get called into a method that displays
                                         //the messages in a JOptionPane.showMessageDialog()
        if (e.getMessage().startsWith("The TCP/IP connection to the host"))
        {
            errors[0] = "SQL CONNECTION FAILED: Please check the server URL you entered to make sure it is correct.";
            cancel = true;
            mGUI.serverNameTextField.setForeground(Color.RED);
        }

        if (e.getMessage().startsWith("Login failed for user"))
        {
            errors[1] = "LOGIN FAILED: You do not have sufficient access to the server.";
            cancel = true;

        }
        if (e.getMessage().startsWith("Cannot open database"))
        {
            errors[2] = "SQL CONNECTION FAILED: Please check the database name you entered to make sure it is correct.";
            cancel = true;
            mGUI.dbNameTextField.setForeground(Color.RED);
        }

        mGUI.reportErrors(errors); //Method where it reports the String[] array of errors
                                   //However, the 'errors' parameter only returns one error
                                   //message at a time, which is the problem.

字符串
谢谢你的帮助!

    • 我更改了if语句,添加了一个AND参数,用于检查特定的错误代码。您可以通过设置断点并查看调试透视图来查找错误代码,也可以像我所做的那样设置print语句来查看错误代码。下面是print语句:
System.out.println(((SQLException) e).getErrorCode());


以下是我的新for语句:

try 
    {
        //attempt connection here
    } 
    catch(SQLException | ClassNotFoundException e)
    {
        if (e instanceof SQLServerException && ((SQLServerException) e).getErrorCode() == 0)
        {
            //code here
        }
        else{
            //code here
        }
        System.out.println(((SQLException) e).getErrorCode()); //Here is the print statement to see the error code.
        if (e instanceof SQLServerException && ((SQLServerException) e).getErrorCode() == 4060)
        {
            //code here
        }else{
            //code here
        }
        if(cancel != true)
        {
            //code here
        }
    }

txu3uszq

txu3uszq1#

你可以用多种方式来做
1具有一个以上具有共同功能的锁扣

}catch (ClassNotFoundException e){
    handleError(e);

}catch (SQLException e){
    handleError(e);
}

字符串
其中handleError将异常作为参数。
您似乎没有做任何其他事情,因此可以将它们组合成一个异常

}catch(Exception e){

}


这将捕获所有内容,但您对错误处理的控制要少得多。

vuktfyat

vuktfyat2#

异常的一般原则是,在最适合处理它们的时候处理它们。
你似乎有非常不同的异常,大概在代码中的某个地方抛出的TCP异常与连接到数据库时抛出的SQLException不一样(我可能错了,因为我不知道代码的其余部分是什么样子的)。因此,一组异常处理程序(每种类型一个)不是更有意义吗?同样来自Bryan Roach,文本消歧不是一个好主意。

try {
...
} catch (java.net.SocketException e) {
 e[0] = "tcp error";
} catch (java.sql.SQLException e) {
 e[1] = "sql exception happened";
}

字符串
另外你的字符串数组似乎有点风险,可能是一个

ArrayList errors = new ArrayList();
errors.add("Some tcp error");
errors.add("Some db error");


然后为您提供错误报告

mGUI.reportErrors(errors.toArray())


将保留您的接口,而不是浪费您必须分配额外的元素到数组和有空条目。我不知道你的问题是什么,但你暗示GUI没有显示多个错误。可能有一个检查在数组中的第一个空元素处停止。当e[2]和e[4]被填充时,它可能会在迭代错误时停止,因为e[3]是空的。我又在假设了因为我不知道那代码是什么样子的

s5a0g9ez

s5a0g9ez3#

从上面的注解来看,听起来你想做的是为你在一个catch块中捕获的各种Exception类型使用不同的逻辑。如果是这样的话,你可以去:

...
catch(ClassNotFoundException | SQLException e) {
    String[] errors = new String[4];
    if (e instanceof ClassNotFoundException) {
       //do something here
    }
    if (e instanceof SQLException) {
       //do something else here
    }
    ...etc
}

字符串
这应该是可行的,但使用多个catch块可能和其他人建议的一样容易:

}catch (ClassNotFoundException e){
    handleError(e);
}catch (SQLException e){
    handleError(e);
}


我无意冒犯,但是代码处理异常的方式可能会在以后引起一些麻烦。举例来说:

if (e.getMessage().startsWith("Cannot open database")) {


这里的代码依赖于抛出异常的支持库来使用相同的文本描述,但是如果您切换到另一个JVM版本,使用不同的数据库驱动程序等,则此描述可能会更改。使用异常类型而不是异常描述可能更安全。

相关问题