being interrupted while joining other threads - java

How should I handle InterruptedException while joining other threads, assuming I don't actually anticipate being interrupted, and there is no sensible thing to do? Just swallow the exception?
try
{
t.join();
u.join();
}
catch (InterruptedException e)
{
// should not happen
}
Or should I put each join in its separate try/catch, so if an InterruptedExeption does happen while joining t, at least u gets a chance of being joined?
try
{
t.join();
}
catch (InterruptedException e)
{
// should not happen
}
try
{
u.join();
}
catch (InterruptedException e)
{
// should not happen
}
Or should I defensively swallow the exceptions in a loop, so I will eventually join both threads, even if some malicious guy tries to interrupt me?
while (true)
{
try
{
t.join();
break;
}
catch (InterruptedException e)
{
// no way, Jose!
}
}
while (true)
{
try
{
u.join();
break;
}
catch (InterruptedException e)
{
// no way, Jose!
}
}
On a side note, is there any case where InterruptedExeption doesn't make my code look ugly? :)

If something shouldn't happen, you probably want to know if it ever does happen - and the best way of making it obvious is often to throw a RuntimeException of some description (e.g. IllegalStateException). If you're not anticipating the possibility of being interrupted, that suggests the system is in a state you're not really happy to support, so I wouldn't then try to keep going - aborting quickly is often the best option here.
You may want to write a helper method which does this for you, to make the calling code cleaner.

Related

Java run code only if no exception is thrown in try and catch block?

How do I make it so the code runs only if there was no exception thrown?
With finally code runs whether there was an exception or not.
try {
//do something
} catch (Exception e) {}
//do something only if nothing was thrown
Here are two ways:
try {
somethingThatMayThrowAnException();
somethingElseAfterwards();
} catch (...) {
...
}
Or if you want your second block of code to be outside the try block:
boolean success = false;
try {
somethingThatMayThrowAnException();
success = true;
} catch (...) {
...
}
if (success) {
somethingElseAfterwards();
}
You could also put the if statement in a finally block, but there is not enough information in your question to tell if that would be preferable or not.
try {
doSomething();
doSomething2();
} catch (Exception e) {
doSomething3();
}
In this example, doSomething2() will only be executed if no exception is thrown by doSomething().
If an exception is thrown by doSomething(), doSomething2(); will be skipped and execution will jump to doSomething3();
Also note, doSomething3() will be executed if there is an exception thrown by doSomething2();
If no exception is thrown, doSomething3(); will not be executed.
Just put the code in the try block. If an exception is thrown, it will skip to the catch block. If no exception is thrown, the code will just run.
try {
someMethodThatMayThrowException();
codeThatShouldBeRunIfNoExceptionThrown();
} catch (Exception e) {...}
An enhancement to the proposed
try {
somethingThatMayThrowAnException();
somethingElseAfterwards();
} catch (...) {
...
}
from the accepted answer. What you should do is:
void foo() {
try {
doStuff();
} catch (...) {
handleException();
}
}
The above feels like overkill to someone who hasn't been exposed to "clean code thinking".
But the point here: you do not want to mix different abstractions within one method. In other words: you don't have one try block, and more code following behind that within the same method.
You make sure that each and any method contains a straight forward path - you avoid anything that complicates your reading flow. As soon as you get used to writing and reading such kind of code you will find that it takes you dramatically less time to understand your code.
Exceptions for flow control is kind of a bad practice. If you insist, use a boolean variable.
boolean thrown = false;
try {
//do something
} catch (Exception e) {
thrown = true;
}
//do something only if nothing was thrown
if (!thrown) {
// do stuff
}
I was trying to solve this exact problem when I came across this question, and the answers here helped me think it through and realize, at least in my particular case, this was the wrong question I should have been asking.
I wanted to create this method because I was already doing it in main() and wanted to do it elsewhere for portability. So I copied a block of code that contained a try/catch block. However, it turns out, I don't want to copy the catch block at all, because if the creation of the Connection failed, I just wanted to fail completely.
It seems obvious now, but I never wanted to actually catch the exception in the first place. That code was only there because I copy and pasted it. So if you find yourself asking this question because you're in a try block and you might not generate a value, then consider if you just wanted to fail completely and not return anything that way this extra code is unnecessary.

making only one of the running threads to execute a catch block?

I have a multi threaded Java program and at times it throws an exception which requires some changes to my network settings. The problem I'm facing is that all the running threads try to do it, which causes problems. Is there a way to make only one of the running threads to execute the code in the catch block?
This is my catch block
catch (ElementNotFoundException e)
{
System.out.println("Element not found!");
e.printStackTrace();
IpManager.changeDSLIp();
}
catch (Exception e)
{
e.printStackTrace();
}
//Define a variable to indicate network settings has been done.
public static boolean NETWORK_SETTINGS_DONE = false;
public static Object LOCK = new Object();
public void doSometing() {
try {
} catch (Exception e) {
synchronized (LOCK) {
if (!NETWORK_SETTINGS_DONE) {
//do some changes to your network settings.
NETWORK_SETTINGS_DONE=true;
}
}
}
}
You need a single central service to handle the change to the network settings so you can prevent multiple changes at the same time and still give reasonable feedback. Your threads or more specific your exception handling code needs to transfer the responsibility to this service and may use it to check the current status to handle the exception in an appropriate way (sounds like the threads would have to wait for new settings).
Something like this might do the trick...
} catch (Exception e) {
synchronized (someCommonObject) {
if (!done) {
// do stuff
}
done = true;
}
}
someCommonObject could be "this" but only if all threads are being handled by that object. otherwise pick some other (possibly static) object. The "done" boolean would have to be static / commonly referenced also.

Handling recoverable and unrecoverable exceptions

Hopefully I can explain this clearly. If I have a main method with lots of steps that can generate different exceptions, some fatal, some not, do I have to catch the "recoverable" ones separately? It seems like that would result in potentially a lot of try/catch blocks, like so:
public static void main (String[] args) {
try {
//...
for (int i=0;someArray.length;i++) {
try{
System.out.println("I = " + i);
doSometing(i);
} catch (RecoverableException e) {
//recover, continue, whatever
//log warning
//keep
}
}//end for loop
try {
doSomethingElse();
} catch (AnotherRecoverableException e) {
//not fatal, keep on chugging
}
//...
//do more stuff that can throw unrecoverable exceptions
} catch (UnrecoverableException e) {
System.out.println("I can't handle this, it's too much!");
e.printStackTrace();
}
}
Is there a better way to do this?
My patterns are to let exceptions propagate when they would represent programming bugs and handle them as closely to the "problem" when you can handle them.
The problem is that many potential Programming bugs throw checked exceptions which is really bad (Checked exceptions are kind of a failed experement, the newer languages have gotten rid of them).
So:
Handle checked and unchecked exceptions that you can deal with immediately.
If you don't know how to handle a checked exception rethrow it as an unchecked exception.
any "top level" loop like in main or a thread should be surrounded by a try/catch/log of "Exception" to ensure that any exception that bubbles up doesn't kill the thread (but log it loudly because it represents an unknown programming bug!)
Any critical loop that should continue regardless of exceptions should have a try/catch/log of "Exception" inside the loop construct so it will continue.
Catch exception, not throwable at this high level. Throwable includes unrecoverable exceptions that you probably never want to catch.
If you really must throw an exception you think you want the caller to catch (try to avoid this--It means you are using Exceptions as code flow!), throw an unchecked exception but document it and have the method "throw" the unchecked exception (it doesn't HAVE to be handled, but this acts as additional documentation/hint).
Just as a background for why I dislike checked exceptions so--it makes code like this happeen:
try {
Thread.sleep(1000);
} catch(InterruptedException e) {}
This can hide some INCREDABLY annoying to find program-flow related bugs. In this case it simply means you might have some thread-control issues, but in others it can mean your code-flow "Magically" vanishes mid-method with no indication whatsoever (because an exception was picked up by a higher level try/catch).
If you are using Java 7 then you can club exceptions in the catch block using pipe as separator. This will reduce your number of catch blocks. But you need to decide how you want to handle them by putting appropriate code in the catch block.
In Java 7, you can do this:
try
{
...
}
catch(Exception1 | Exception2 | Exception3 e)
{
//Handle
}
catch(Exception4 | Exception5 | Exception6 e)
{
//Handle differently
}
You can use. defaultUncaughtExceptionHandler, but it only triggers if the Thread doesn't have a uncaughtExceptionHandler set.
For java versions other than 7, a cleaner approach is to handle exceptions in called methods. This makes code readable as shown below:
doSomething(int i){
//code
try{
//code
}catch(Exception1 e1){
//handle
}
catch(Exception2 e2){
//handle
}
}
doSomethingElse(){
//code
try{
}catch(Exception1 e1){
//handle
}
catch(Exception2 e2){
//handle
}
}
public static void main (String[] args) {
for (int i=0;someArray.length;i++) {
doSometing(i);
}//end for loop
doSomethingElse();
}
I do not recommend using generic Exception to catch all errors in one block. This makes difficult to know specific exceptions and prevents specific handling of them.

calling a blocking method call with timeout in java

I want to call a method in java which blocks for some reason. I want to wait for the method for X minutes and then I want to stop that method.
I have read one solution here on StackOverflow which gave me a first quick start. I am writing that here :-
ExecutorService executor = Executors.newCachedThreadPool();
Callable<Object> task = new Callable<Object>() {
public Object call() {
return something.blockingMethod();
}
};
Future<Object> future = executor.submit(task);
try {
Object result = future.get(5, TimeUnit.SECONDS);
} catch (TimeoutException ex) {
// handle the timeout
} catch (InterruptedException e) {
// handle the interrupts
} catch (ExecutionException e) {
// handle other exceptions
} finally {
future.cancel(); // may or may not desire this
}
But now my problem is, my function can throw some Exception which I have to catch and do some task accordingly. So if in code the function blockingMethod() thorws some exception how do I catch them in Outer class ?
You have everything set up to do that in the code you provide. Just replace
// handle other exceptions
with your exception handling.
If you need to get your specific Exception you get it with:
Throwable t = e.getCause();
And to differentiate between your Exceptions you can do like this:
if (t instanceof MyException1) {
...
} else if (t instanceof MyException2) {
...
...
In cause of ExecutionException instance, I suppose.
In the ExecutionException catch block: e.getCause()
https://docs.oracle.com/javase/6/docs/api/java/lang/Throwable.html#getCause
thread.sleep(x millisecods) will stop the thread for x milliseconds, then it will resume. The other way to do it is to call thread.wait(x) (with a timeout value for x) and then call thread.notify() to "wake" the sleeping thread.

Handling Multiple Exceptions within a Method

I am currently working on the maintenance of a piece of code that is a little bit "Exception Happy." Basically, ever method or anything throws Exception. I'm going to work to take care of that, but, in the meantime, I am wondering what is the best way to handle individual exceptions within a smaller block of code, such as a method. Is it better to do something like this:
public void aMethod()
try {
//Lots of code in here. Many lines.
} catch(Exception e) {
// TODO - Handle All Exceptions, but fairly generically
}
}
Or something like this:
public void bMethod() {
try {
// One line of code.
} catch(Exception e) {
// TODO - Handle a specific Exception (may even involve rethrowing it with more information)
}
// More code.
try {
// Another line of code.
} catch(Exception e) {
// TODO - Handle another specific exception.
}
}
I realize this is a pretty basic question, but after looking at hundreds of methods with Exceptions coming out of every one, I'm starting to wonder how best to handle all of them and what a best practice may be here.
First off, you should only put code in try/catch blocks that is exception worthy. For instance, having an unexpected value is not necessarily an exception, but trying to read from a file that doesn't exist is.
To answer your main question, you should put the exceptionable code in the same try {} block and catch specific questions in order of granularity in multiple catch blocks after the main try.
//Regular code that doesn't need to be covered by a try/catch block
try {
//critical code only
} catch (NullPointerException npe) {
//Code
} catch (RandomException re) {
//code
} catch (Exception e) {
//code
}
The answer to your question is: it depends.
if the code in the try block is coherent where it makes no sense to proceed in the event of an error, the first approach is best
if the code is taking seperate steps that are relatively unrelated (parsing numbers for instance) and can be recovered without aborting the rest of the method the seconds appraoch makes sense
A general remark on the code you inherited; it sounds like exceptions are abused to pass state around, I would refactor so that exceptions are caught at the spot where they can be handled and introduce return values or attributes to handle the state.
your bMethod isn't very useful illustration. Try to reprase it. Anyway, you have two options:
catch exceptions and log them.
catch exceptions and throw new RuntimeException(ex) (rethrow a runtime exception, setting the original as a cause)
Also, you will need to differentiate between exceptions. If your system has many custom exceptions, they are probably defined for a reason, and specific behaviour is expected when one of them is thrown.
If the try/catch block isn't adding useful information, just allow the method to throw the exception and have it handled where the caller can sensibly do something with the exception. This could cut down the number of try/catch significantly (by an order of magnitude).
BTW a trick for rethrowing any exception is.
try {
// do something
} catch (Throwable t) {
Thread.currentThread().stop(t); // rethrow any exception.
}
In addition to the suggestions already made you may also want to consider extracting try/catch blocks from the "meat" of the function.
public void delete(Page page) {
try {
deletePageAndAllReferences(page);
}
catch (Exception e) {
logError(e);
}
}
private void deletePageAndAllReferences(Page page) throws Exception {
deletePage(page);
registry.deleteReference(page.name);
configKeys.deleteKey(page.name.makeKey());
}
private void logError(Exception e) {
logger.log(e.getMessage());
}
This lets you focus your attention on the function you are really interested in without the exception handling getting in your way.

Categories