Home > Software engineering >  Java CountDownLatch.await() throws Exception "not compatible with throws clause in Runnable.run
Java CountDownLatch.await() throws Exception "not compatible with throws clause in Runnable.run

Time:06-18

I implemented my own Runnable.run(), it tells me to catch InterruptedException. Then I added it,

    private final CountDownLatch start = new CountDownLatch(1);
    private final int eCount = ...;
    public void run(){
        for(int e = 0;e<eCount;  e){
            new Thread(new Runnable()
                {
                    @Override
                    public void run() throws InterruptedException{
                        start.await(); // 
                    }
                }).start();
        }

But compile error is now:

Exception InterruptedException is not compatible with throws clause in Runnable.run()Java(67109266)

What does it mean by "not compatible with throws clause". How to fix this issue?

CodePudding user response:

The interface Runnable exposes this method:

public abstract void run();

This method throws nothing (only unchecked exceptions).

The message you get means you can't throw checked exceptions (such as InterruptedException) inside this method cause otherwise, it doesn't match the run() signature.

Generally speaking, if you @Override a method of an interface / abstract class, it is necessary that you respect the signature that is imposed by it and this includes the throws list (you can not throw an exception that is declared if you wish, but you can't throw an exception that is not declared).

About how to fix, you can wrap your checked exception inside an unchecked exception:

@Override
public void run() {
    try {
        start.await();
    } catch (InterruptedException e) { //<-- catch the checked exception
        throw new RuntimeException("Interrupted", e); //<-- wrap it into an unchecked exception (you can also create your own, which I suggest, instead of using the generic RuntimeException)
    }
}
  • Related