Несколько операторов с участием с одинаковыми типами исключенийJAVA

Программисты JAVA общаются здесь
Anonymous
Несколько операторов с участием с одинаковыми типами исключений

Сообщение Anonymous »

Я все искал, чтобы получить ответ на это, и мне еще предстоит его найти. Мой босс хочет иметь возможность войти в все поля, а затем проверить, являются ли они действительными записями, то если есть какие -либо недействительные записи, он хочет, чтобы я покраснел текст красный, указывая, что поле недействительное. У меня есть оператор try Catch ClassNotFoundException и SQLexception. Поскольку есть несколько полей, которые необходимо проверить, я пытался иметь набор операторов IF для проверки информации об соединении. Вот приведенный ниже код, я надеюсь, что это имеет смысл ... < /p>

//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 * ** * **
Я нашел решение, так что это поможет кому -то. Я изменил свои операторы IF, чтобы добавить и проверку аргументов для конкретного кода ошибки. Вы найдете код ошибки, либо установив точку перерыва и просмотрев перспективу отладки, либо вы можете сделать то, что я сделал, и установить оператор печати, чтобы увидеть код ошибки. Вот утверждение печати: < /p>

System.out.println(((SQLException) e).getErrorCode());
< /code>

Вот мой новый для операторов: < /p>

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


Подробнее здесь: https://stackoverflow.com/questions/174 ... tion-types

Вернуться в «JAVA»