0

I have a class that allows to download a file from the internet:

public String download(String URL) {

try {
 if(somethingbad) {
  // set an error?
  return false; 
 }
}
//...
catch (SocketException e) {
 e.printStackTrace();
}
catch (UnsupportedEncodingException e) {
 e.printStackTrace();
}
catch (ClientProtocolException e) {
 e.printStackTrace();
}
catch(InterruptedIOException e) {
e.printStackTrace();
}
catch (IOException e) {
 e.printStackTrace();
}
}

Now, I am calling this function in another class and i want to show a message that will help me figure out why this will not work.

what can i do to display something like this?

HTTPReq r = new HTTPReq("http://www.stack.com/api.json");    
if(r.err) {
 showMessage(getMessage());
}

and the getMessage() will return the SocketException or IOException or even "empty url" if the URL is empty.

2 Answers 2

2

First of all I do not think you need all these:

SocketException, UnsupportedEncodingException, ClientProtocolException since they extend IOException

but if you want you can do this:

public String download(String URL) throws IOException, Exception {

    try {
        if(somethingbad) {
            throws new Exception("My Message);
        }
    }
    catch (IOException e) {
        throw e;
    }
}

And then in your other file:

try {
    // some stuff
}
catch (Exception e) {
    // do something with e.getMessage();
}
catch (IOException e) {
    // do something with e.getMessage();
}
Sign up to request clarification or add additional context in comments.

1 Comment

catch(IOException) should go before catch(Exception). Otherwise IOExceptions will go into the first catch block.
2

Instead of just doing e.printStackTrace() inside the catch blocks, throw the exception back like so:

throw e;     

Then you can surround the calling code like so:

try {
    HTTPReq r = new HTTPReq("http://www.stack.com/api.json");
} catch (Exception e) {
    // Show error message
}

4 Comments

and i would just do : e.getMessage() from my other class?? Also, how would i trigger a getMessage() if the if(somethingbad) { fails?
You have to modify the signature of download method to indicate that it throws exceptions using the throws clause. An IDE should help you with the proper syntax.
I am using android studio and still don't get it
> and i would just do : e.getMessage() from my other class?? You could if you wanted to get the message inside the catch block. > Also, how would i trigger a getMessage() if the if(somethingbad) { fails? What sets the value of somethingbad? If download method throws an exception, the control will go into the appropriate catch block. The method will not continue to execute.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.