This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

This article, the original problem: translate for stackoverflow question stackoverflow.com/questions/3…

Issue an overview

What is the difference in how you handle InterruptedException? What’s the best way to do that?

try{
 / /...
} catch(InterruptedException e) { 
   Thread.currentThread().interrupt(); 
}
Copy the code

or

try{
 / /...
} catch(InterruptedException e) {
   throw new RuntimeException(e);
}
Copy the code

Also: I would like to know in which cases these two situations are used.

Best answer

You might ask this question because you have called the method that raises InterruptedException.

First, you should see that it throws InterruptedException: part of the method signature and the possible result of calling the method you are calling. Therefore, first accept the fact that InterruptedException is a fully valid result of the method call.

Now, what should your method do if the method you are calling throws such an exception? You can find out by considering whether it makes sense to throw InterruptedException for the method you are implementing. In other words, is InterruptedException a sensible result when calling your method?

  • If so, throw InterruptedException as part of the method signature, and let the exception propagate (that is, not catch it at all).
int computeSum(Server server) throws InterruptedException {
    // Any InterruptedException thrown below is propagated
    int a = server.getValueA();
    int b = server.getValueB();
    return a + b;
}
Copy the code

If not, then you should not declare your method using throws InterruptedException, and (must!) The exception should be caught. Now, two things to keep in mind in this situation:

void printSum(Server server) {
     try {
         int sum = computeSum(server);
         System.out.println("Sum: " + sum);
     } catch (InterruptedException e) {
         Thread.currentThread().interrupt();  // set interrupt flag
         System.out.println("Failed to compute sum"); }}Copy the code