How to quit from a catch exception - java

I'm using java to connect to http server. All is fine. Of course I catch exceptions (SocketTimeoutException, ConnectException, IOException). But my problem is when (for example) an ConnectException occurs, the app stay stucked. I can't anymore continue in an other part of program... I tried "return ..", System.exit (but I don't want to exit from application). Any idea ?
The skeleton prog looks like this:
boolean metod_to_check_http_server(){
try{
Create_connection(URL);
Set_Time_Out(3000);
open_HTTP_Connection();
Close_Connection();
return true; // All this part is fine...
}
catch (EXCEPTIONS)
{ // Here I know I have connection problem
// how could I return to main prog from here ?
// return false ? not work...
// System.exit(..); // too violent !
// so ?
}

If you add finally block to your try - catch statement you can continue your flow
try
{
}
catch{
}
finally{
}

Try to put finally block in you code after the catch one.

Your question cannot be answered without knowing more about your program and environment, but it might be a good idea to inform the user about the connection failure, for example in a dialog saying "Connection failed". And don't forget to close any open connections in a finally block.

You should do exception handling yourself, and return a false if connection fails or is invalid....
boolean method_to_check_http_server(){
try{
Create_connection(URL);
Set_Time_Out(3000);
open_HTTP_Connection();
return true; // All this part is fine...
} catch (EXCEPTIONS) {
displayError();
return false;
} finally {
Close_Connection();
}
}
As you can see, I made sure that my connection is closed (in the finally block) so that I don't leave opened sockets running in some OS thread somewhere.

Related

Catch connection timeout and page not found exception?

I am using a third party api to get user authentication in spring.
I need to catch the exceptions that occur when trying to connect to that api, like connection time out and page not found (if their server is down).
Right now I am trying to do this with below code. Is this sufficient to catch these exceptions?
public boolean userAuthentication(String userName) {
try {
if(hasAccess(userName)) {
return true;
} else {
return false;
}
} catch (IOException e) {
logger.info("exception occured "+ e);
return false;
}
}
Here hasAccess is the third party api, I cannot change that method. Whereas I need to catch these exception and give appropriate response to the user.
does hasAccess(String) define any throws statement?
Does it define that it throws IOException?
Do you have the access to the source code of this method? If you do then you can go and and check if they are handling any exceptions thrown or they are re-throwing any runtime exceptions.
To be on safer side, you should catch runtime exceptions, as the error is unpredictable for you, so you can gracefully handle errors.
It is impossible to tell whether this is sufficient without looking at the implementation of hasAccess(), since that is the function that will throw the error.
However, if you really need to catch this exception, you can always use
try {
if (hasAccess(userName)){}
} catch (Exception e) {
//caught
}
This isn't always good practice, since Exception will catch every exception, but it is a solution if you're looking for one.

Execute server call if first fails in java

I have two ids (id1, id2) and I want to fetch data from server if first fails.
try
{
loadData1(id1);
}
catch(Exception e)
{
loadData2(id2);
}
Is this a good practice or is there any alternative for this?
This is not a good practice. Try to use the catch block for handling the error/exception and logging the error information. You can have a condition check to see if the loadData1(id1); operation is a success so that in the next try-catch block you can add the logic loadData2(id2);
boolean loadSuccess=false;
try
{
loadSuccess=loadData1(id1);
}
catch(Exception e)
{
//error handling or logging code goes here
}
if(!loadSuccess)
{
try
{
loadData2(id2);
}
catch(Exception e)
{
//error handling or logging code goes here
}
}
loadData1 fails when it throws an exception. But loadData2 is there to handle it as long as -
loadData2 function call in catch is again wrapped in an effective try-catch.
loadData2 is function that already has exception handling implemented.
The rest of the code should continue execution if one of the conditions is met.

Multiple catch statements with the same exception types

I've been looking all over for an answer to this and have yet to find one.
Basically I am trying to connect to a database server through a GUI. My boss wants to be able to enter all fields and then check to see if they are valid entries, then if there are any invalid entries, he wants me to turn the text red, indicating that the field is invalid. I have the try statement catch ClassNotFoundException and SQLException. Because there are multiple fields that need to be checked, I have tried to have a set of if statements to check the connection info. Here is the code below, I hope this makes sense...
//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.
Thanks for any help!
****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());
Here are my new for statements:
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
}
}
You can do it in multiple ways
1 having more than one catch with a common function
}catch (ClassNotFoundException e){
handleError(e);
}catch (SQLException e){
handleError(e);
}
where handleError takes the exception as the argument.
You dont seem to do anything else so you can just combine them both into a single exception
}catch(Exception e){
}
which will catch everything but you have MUCH less control over the error handling.
A general principle of exceptions is that they are handled at the point they are best abled to be handled.
You seem to have very disparate exceptions and presumably a TCP exception thrown somewhere in the code is not the same as the SQLException thrown when connecting to a database (I might be wrong here since I don't know what the rest of the code looks like). So would not a set of exception handlers, one for each type make more sense. Also to reite from Bryan Roach, text disambiguation is not a good idea.
try {
...
} catch (java.net.SocketException e) {
e[0] = "tcp error";
} catch (java.sql.SQLException e) {
e[1] = "sql exception happened";
}
Also your string array seems a bit risk, possibly a
ArrayList errors = new ArrayList();
errors.add("Some tcp error");
errors.add("Some db error");
and then for you error reporting
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
From the comments above it sounds like what you want to do is have different logic for the various Exception types you are catching within a single catch block. If this is the case, you could go:
...
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
}
This should work, but it's probably just as easy to use multiple catch blocks as others have suggested:
}catch (ClassNotFoundException e){
handleError(e);
}catch (SQLException e){
handleError(e);
}
I don't mean any offense, but the way the code handles exceptions might cause some headaches down the road. For example:
if (e.getMessage().startsWith("Cannot open database")) {
Here the code relies on the supporting library that throws the exception to use the same text description, but this description might change if you switch to another JVM version, use a different database driver, etc. It might be safer to go by the exception type, rather than the exception description.

Socket read() and ready() interlock, client disconnect detection

Ok my issue is simple. I am trying to make simple chat but i feel that detection of disconnected client from server is mandatory. Chat works fine (without such detection) when i use simple:
if (this.in.ready()) //preinitialized buffered reader
this.dataIn=this.in.readLine();
I have browsed lots of websites/questions posted here and i read that ready() should be ommited since it blocks everything, that may be true since when i delete this ready() my chat no longer works, however it enables client disconnected detection.
In order to reach my goal i need to test if BufferedReader recieves null through readLine() but this does not work as it should either.
if (this.in.readLine()!=null){ //1. check if client disconnected
if (this.in.ready()) //2/
this.dataIn=this.in.readLine(); //3.
}
else
this.notice="Client disconnected!";
Now what happens when i apply code presented above. Initial if (1) is blocking the inner ready() (line 2) which is required to read actual message send over socket (3).
The other "order" does not work:
if (this.in.ready()){
this.dataIn=this.in.readLine();
}
else if (this.in.readLine()!=null)
this.notice="Client disconnected!";
This one also does not allow to send messages through socket.
*Yes, sending/recieving is realized in separate thread
*BufferedReader is initialized only once
Thread source code (if any1 would need it in order to take a look):
#Override
public void run() {
try {
if (this.isServer){
this.initServer();
this.initProcessData(sSocket);
}
else if (!this.isServer){
this.initClient();
this.initProcessData(clientSocket);
}
this.initDone=true;
} catch (IOException ex) {
Logger.getLogger(NetClass.class.getName()).log(Level.SEVERE, null, ex);
}
while(this.initDone){
try {
Thread.sleep(100);
if ((!this.dataOut.isEmpty())&&(this.dataOut!="")){
this.out.println(this.dataOut);
this.out.flush();
this.dataOut = "";
}
if (this.in.ready())
this.dataIn=this.in.readLine();
}
catch (IOException ex) {
Logger.getLogger(NetClass.class.getName()).log(Level.SEVERE, null, ex);
}
catch (InterruptedException ex) {
this.initDone=false;
Logger.getLogger(NetClass.class.getName()).log(Level.SEVERE, null, ex);
}
//System.out.println(this.notice);
}
}
The worst thing is that i have either proper detection of client disconnected or i have working chat.
Can anyone enlight me what should i do in order to combine those two together? Any help greatly appreciated.
Consider using java.io.ObjectInputStream and java.io.ObjectOutputStream. Use the blocking read() method in a separate worker thread, and loop until it returns -1 or throws an exception. Send String objects back and forth. In that way, you can also send messages with line feeds.

Catching some exceptions but ignoring others - why doesn't this work?

I have something similar to this.
void func() {
try {
//socket disconnects in middle of ..parsing packet..
} catch(Exception ex) {
if(!ex.getMessage().toString().equals("timeout") || !ex.getMessage().toString().equals("Connection reset")) {
debug("Exception (run): " + ex.getMessage());
ex.printStackTrace();
}
}
Why is it that when I get a connection reset exception or a timeout exception, it still goes inside the condition. I tried without toString and with no luck.
You shouldn't catch all exceptions and then test the error message of the exception. Instead only catch those exceptions that you intend to handle - for example SocketTimeoutException.
catch (SocketTimeoutException ex)
{
// Do something...
}
With your current code you may be catching some other type of exception that you weren't expecting. Currently you will just ignore this exception, not even logging it. This can make it very difficult to debug what is going on. If you have an exception that you can't handle you should either rethrow it or log it.
I want to catch all exceptions
If you really want to do that then you can write your code as follows:
catch (SocketTimeoutException ex)
{
// Do something specific for SocketTimeoutException.
}
catch (Exception ex)
{
// Do something for all other types of exception.
}
Regarding your specific error, you have written:
!a.equals(b) || !a.equals(c)
This expression always evaluates to true. What you meant was:
!a.equals(b) && !a.equals(c)
Or equivalently:
!(a.equals(b) || a.equals(c))
Note that by rewriting your code as I suggested above you completely avoid having to write this complicated boolean expression.
It's really not safe to rely on exceptions messages to know what is the cause of your exception.
In your case you can try to catch more specific exceptions, such as SocketTimeoutException and the classic IOException :
void func() {
try {
//socket disconnects in middle of ..parsing packet..
} catch(SocketTimeoutException ex) {
//In case of Time out
} catch(IOException ex){
//For other IOExceptions
}
}
Sources :
[Socket.connect()][3]
Even if you prefer to seek informations in exceptions messages, you shouldn't check if the message simply is equal to "timeout" but if the message contains "timeout"
[3]: http://download-llnw.oracle.com/javase/6/docs/api/java/net/Socket.html#connect(java.net.SocketAddress, int)

Categories

Resources