Catch all exceptions within a thread - java

Below is the code I have developed for a thread.
int i;
Thread thread = new Thread()
{
#Override
public void run() {
try {
while(true) {
sleep(10000);
i++
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
Is there any possible way I can use any other catch or exception to catch all possible crushes within it?
Thank you in advance!

Just have catch (Exception ex) as well as catch (InterruptedException e)

It seems that only exception that block can throw,you have already handled but for safer side you can catch parent exception too i,e (Exception e) as below :
try {
//stuff
}
catch (InterruptedException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}

Related

narrower catch and broader catch inside of it in Java

I have a following nested try - catch in Java as you see below.
One of my concern is that
First ( and third ) catch is InterruptedException ( and Throwable ) and we have general Exception in this catch block.
I'm wondering this exception structure makes sense or not ( ie.
narrower outside catch, and broader inside catch ).
Catch blocks don't throw an exception, it's just logging.
if this structure
is not good, is there a better way?
public void run() {
try {
} catch (InterruptedException ex) { // narrower
....
try {
...
} catch (Exception e) { // broader
...
} finally {
...
}
} catch (ShutdownSignalException shutdownException) {
try {
} catch (InterruptedException ignored) {
}
} catch (Throwable ex) {
try {
} catch (Exception e) {
}
try {
} catch (Exception e) {
} finally {
}
}}}

Java handle errors & exceptions

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.
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();
}
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
}

How to catch all exceptions except a specific one?

Is it possible to catch all exceptions of a method, except for a specific one, which should be thrown?
void myRoutine() throws SpecificException {
try {
methodThrowingDifferentExceptions();
} catch (SpecificException) {
//can I throw this to the next level without eating it up in the last catch block?
} catch (Exception e) {
//default routine for all other exceptions
}
}
/Sidenote: the marked "duplicate" has nothing to do with my question!
void myRoutine() throws SpecificException {
try {
methodThrowingDifferentExceptions();
} catch (SpecificException se) {
throw se;
} catch (Exception e) {
//default routine for all other exceptions
}
}
you can do like this
try {
methodThrowingDifferentExceptions();
} catch (Exception e) {
if(e instanceof SpecificException){
throw e;
}
}

How to deal with timeout exception in Java?

Here is my code:
private void synCampaign() {
List<Campaign> campaigns;
try {
campaigns = AdwordsCampaign.getAllCampaign();
for(Campaign c : campaigns)
CampaignDao.save(c);
} catch (ApiException e) {
try {
Thread.sleep(5000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
synCampaign();
e.printStackTrace();
} catch (RemoteException e) {
try {
Thread.sleep(5000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
synCampaign();
e.printStackTrace();
}
}
AdwordsCampaign.getAllCampaign() tries to get some remote resource. This may throw a RemoteException because the internet connection times out. When the exception is caught, I just want the thread to sleep for a while, then try to get the remote resource again.
Is there a problem with my code? Or is there a better way?
Nothing really wrong, but the (potentially infinite) retry loop with recursion (and the stack growing) makes me a little nervous. I'd write instead:
private void synCampaignWithRetries(int ntries, int msecsRetry) {
while(ntries-- >=0 ) {
try {
synCampaign();
return; // no exception? success
}
catch (ApiException e ) {
// log exception?
}
catch (RemoteException e ) {
// log exception?
}
try {
Thread.sleep(msecsRetry);
} catch (InterruptedException e1) {
// log exception?
}
}
// no success , even with ntries - log?
}
private void synCampaign() throws ApiException ,RemoteException {
List<Campaign> campaigns = AdwordsCampaign.getAllCampaign();
for(Campaign c : campaigns)
CampaignDao.save(c);
}
This looks OK except the repetition of code in catch block(be sure of number of retries you want). You may want to create a private method to handle your exception as below:
private void synCampaign() {
List<Campaign> campaigns;
try {
campaigns = AdwordsCampaign.getAllCampaign();
for(Campaign c : campaigns)
CampaignDao.save(c);
} catch (ApiException e) {
e.printStackTrace();
waitAndSync();
} catch (RemoteException e) {
e.printStackTrace();
waitAndSync();
}
}
private void waitAndSync(){
try {
Thread.sleep(5000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
synCampaign();
}
You indeed cannot catch it as a SocketTimeoutException. What is possible is to catch the RemoteException, retrieve it's cause and check if that's an instanceof SocketTimeoutException.
try{
// Your code that throws SocketTimeoutException
}catch (RemoteException e) {
if(e.getCause().getClass().equals(SocketTimeoutException.class)){
System.out.println("It is SocketTimeoutException");
// Do handling for socket exception
}else{
throw e;
}
}catch (Exception e) {
// Handling other exception. If necessary
}

Own exception in javame

Could I replace all the catches with one (self written) catch and switch between the types of exceptions caught in the self written one? That way I can easily put debugging on and of in the exception.
try {
int recordId = recordstore.addRecord(data, 0, data.length);
} catch (RecordStoreFullException e) {
e.printStackTrace();
System.out.println("debuginfo");
} catch (RecordStoreNotOpenException e) {
e.printStackTrace();
System.out.println("debuginfo");
} catch (RecordStoreException e) {
e.printStackTrace();
System.out.println("debuginfo");
} catch (NullPointerException e) {
e.printStackTrace();
System.out.println("debuginfo");
} catch (Exception e) {
e.printStackTrace();
System.out.println("debuginfo");
}
Is there any reason you don't do this?
try {
int recordId = recordstore.addRecord(data, 0, data.length);
} catch (Exception e) {
// or use a logging framework.
System.err.println("debuginfo");
e.printStackTrace();
}

Categories