Search code examples
androidandroidhttpclient

HttpHostConnectException - How can I catch it right?


I have a HttpHostConnectException... That is okay, because the server is offline. So I want to mange to catch this exception for the situation, the server will be down.

But if I use

catch (HttpHostConnectException e){
            e.printStackTrace();
}

Nothing happens and the exception will be kill the progess. So how can I catch "unreachable" servers? Thank your for your time and help ;)


Solution

  • Calling e.printStackTrace(); will Kill your app as the exception is not handled

    e.printStackTrace(); will print the exception on to the logcat and Will show an error or will crash you app

    Either you can display the exception as string or Make static text as toast saying server unreachable

    catch (HttpHostConnectException e)
    
    {
    
     Toast.makeText(getApplicationContext(), "Server Unreachable ", Toast.LENGTH_LONG).show();
    
    }
    

    if you want to show what was the actual problem / exception that was caused use

    catch (HttpHostConnectException e)
    
    {
    
     Toast.makeText(getApplicationContext(), "Connection Timeout Reason "+string.ValueOf(e), Toast.LENGTH_LONG).show();
    
    }
    

    By doing this your app will not kill itself and proceed to the next line of your code

    you can also do this

    Log.v(locat,  exception.toString());