Question

I want to throw the following exception to another method, but I don't know how to achieve this correctly.

  public void startTimeoutHandler() throws TimeoutException
  {
    timer = new Timer();
    timerTask = new TimerTask()
    {
      @Override
      public void run()
      {
        throw new TimeoutException();        
      }
    };
  }

Thank you!

Était-ce utile?

La solution

  • A TimerTask is actually implementation of Runnable which is a fairly limiting abstraction; run() can not return a value or throw checked exception .

  • use Callable<V>: which is also designed for classes whose instances are potentially executed by another thread but unlike Runnable, it's call() method can return result and throw checked exception

    class MyTask implements Callable<Integer>{
    
      @Override
      public Integer call() throws TimeoutException{
        throw new TimeoutException(); 
      }
    }
    
    void usingCallable(MyTask e) {
        e.call(); // error: must catch Exception
    }
    
  • For scheduling the task ScheduledThreadPoolExecutor: An ExecutorService that can schedule commands to run after a given delay, or to execute periodically. It has a nice function:

     <V> ScheduledFuture<V>  schedule(Callable<V> callable, long delay, TimeUnit unit)
    

Autres conseils

As far as I understand you want to interrupt another thread execution by throwing an exception in it. This is impossible. The only way to interfere with another thread execution in Java is to interrupt it.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top