Search code examples
javaexceptionrunnablepacketdatagram

Throwing exception in runnable


So I am trying to send a packet once every 3 seconds and have tried using Schedule Executor service like this:

ScheduledExecutorService exec = Executors.newScheduledThreadPool(1);
exec.scheduleWithFixedDelay(new broadcast(), 0, 3, TimeUnit.SECONDS);

However to be able to send a packet an exception needs to be throw. I'm struggling to find a way to be able to throw this exception. I've tried encapsulating it in a try, catch statement but no luck.

static class broadcast implements Runnable{
    public void run() {
        Iterator iterator = hash.keySet().iterator();
        while(iterator.hasNext()){
            char c = iterator.next().toString().charAt(0);
            int[] a = hash.get(c);
            int sendPort = a[1];
            byte[] buffer = new byte[1024];
            buffer = linkState.toString().getBytes();
            System.out.println(a[0] + " " + a[1]);
            DatagramPacket sent = new DatagramPacket(buffer, buffer.length, sendAddress, sendPort);
            send(sent);  //this line here is the problem
        }
    }
}

private static void send(DatagramPacket sent) throws Exception{
    socket.send(sent);

}

Thanks for any help.


Solution

  • If you really need to throw an exception, yo can surround the entire run() block with a catch for exception and just encapsulate any catched exception inside a RuntimeException or any existing subclass of it (you can also create one). Another option is doing so only inside your method (if you just want to propagate your method's exceptions. I'm not really sure about what you are looking for, but hope it helps.

    Usually you'll want to throw a checked exception only when the one who executes it will be able of doing something if the exception is thrown. If there's no possible "counter action" it's always better to throw an unchecked one. In this case, as your method is private and only used inside your run() method, I see no point on throwing a checked exception, so I would just encapsulate it inside a RuntimeException like this:

    EDIT: as Marko Topolnik points, this wraps al the unchecked exceptions being thrown by socket.send, so you can just rethrow all the unchecked first:

    private static void send(DatagramPacket sent) throws Exception{
        try{
            socket.send(sent);
        }catch(RuntimeException e){
             throw e;
        }catch(Exception e){
             throw new RuntimeException("error sending package through socket", e);
        }
    }
    

    Check this article for more information about checked and uncheked exceptions usage.