Search code examples
javatry-catchthread-sleep

Java: Is it possible to make try/catch shorter?


For example:

try {
        Thread.sleep(333);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

can I use the above try/catch in some kind of way using a created method like trySleep(Thread.sleep(333)); that'll do the exact same as the original try?

A example of use:

public class Test implements Runnable {

    public Test() {
        Thread thisThread = new Thread(this);
        thisThread.start();
    }

    @Override
    public void run() {
        while (true){
            System.out.println("Testing");
            trySleep(Thread.sleep(333));
        }
    }

    public void trySleep(/*Thread object*/){
        //Code for try/catch
    }

    public static void main(String[] args) {
        new Test();
    }

}

Of course the above code won't compile, it's just for the question.

The reason I want this kinda thing is because I find the try/catch things to be so messy and is quiet annoying to read.


Solution

  • You could wrap Thread.sleep in a function that re-throws any exception as a runtime exception (or any uncaught exception).

    public static void trySleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            throw new RuntimeException("Interrupted during sleep", e);
        }
    }