English 中文(简体)
多种渔获量说明,有相同的例外类型
原标题:Multiple catch statements with the same exception types

我一直期待大家对此作出回答,尚未找到答案。

基本上,我试图通过全球调查股与数据库服务器连接。 我的 b想能够进入所有领域,然后检查它们是否为有效条目,然后看是否有任何无效条目,他想要我改写案文,指出外地是无效的。 我有“NotFoundException”和“Exception”级的试卷。 由于有多个领域需要检查,我试图有一套记录,以便检查有关情况。 下面是《法典》,我希望这一点是有意义的......。

    //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.

感谢任何帮助!

****EDIT****** I found a solution, so hopefully this will help someone. I changed my if statements to add an AND argument checking for the specific error code. You find find the error code by either setting a break point and looking at the debug perspective, or you can do what I did and set a print statement to see the error code. Here is the print statement:

    System.out.println(((SQLException) e).getErrorCode());

下面是我的新发言:

    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
        }
    }
问题回答

你们能够以多种方式做到这一点。

1 having more than one catch with a common function

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

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

处理 傲慢地将例外视为理由。

你们似乎会做任何其他事情,因此,你可以把两者合并为一个单一的例外。

}catch(Exception e){

}

这将使所有东西都得到控制,但你对错误处理的控制较少。

例外的一般原则是,这些例外情况是在最能够处理的时候处理的。

你似乎有非常不同的例外,假定在守则中将某个地方推倒的TCP例外与KQException在连接数据库时所投的除外(我在这里可能是错误的,因为我不知道该守则的其他内容。 因此,不会有一套例外处理器,每类处理就更有意义。 同样,从布赖恩·罗瓦特中重申,案文的模糊不清并不是一个好的想法。

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())

would preserve your interface and not waste you having to allocate extra elements to the array and have empty entries. I don t know exactly what your question is, but you allude to the GUI not displaying multiple errors. Possibly there is a check which stops at the first empty element in an array. Say e[2] and e[4] is populated, it might stop when it iterates over the errors as e[3] is empty. I m presuming again since I don t know what that code looks like

从以上评论来看,与你想要做的一样,你在单一捕获区范围内收集的各种例外类型有不同的逻辑。 如果情况如此,你可以:

...
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 (ClassNotFoundException e){
    handleError(e);
}catch (SQLException e){
    handleError(e);
}

我不说任何罪行,但守则处理例外情况的方式可能会造成一些头疼。 例如:

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

在这里,该守则依靠的是提供例外的辅助图书馆,以使用相同的文字描述,但如果你转向另一个证书版本,使用不同的数据库驱动器,这种描述可能会发生变化。 采用例外类型,而不是例外描述,可能比较安全。





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...