1

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.

FOD
  • 333
  • 6
  • 16

7 Answers7

2

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);
    }
}
axblount
  • 2,639
  • 23
  • 27
  • I alway thought that the Thread.sleep had to be in the Thread it was running in? For like if you call it in the construtor `Test()` it wouldn't work. – FOD Apr 05 '15 at 23:07
  • 2
    @FOD When you call `trySleep` from inside `run` you're calling it in the current thread. It doesn't matter where the function is defined. – axblount Apr 05 '15 at 23:08
1

I don't get the question. If you add the three lines into the trySleep-method Body, you get a method, which will let the Thread sleep.

So the answer is yes.

By the way: You wrote an endless sleeping loop

Christian Kuetbach
  • 15,850
  • 5
  • 43
  • 79
  • I know it was endless, it was just a quick example I chose to made, anything else in the example would of been pointless and unrelated. – FOD Apr 05 '15 at 23:07
  • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. – Harshal Patil Apr 06 '15 at 04:16
  • 1
    @HarshalPatil: The part about "If you add the three lines into the trySleep-method" was the answer. I had some problem with the question, because the answer was included to the question. – Christian Kuetbach Apr 06 '15 at 18:06
  • Ohh i thought it is just comment anyways up – Harshal Patil Apr 07 '15 at 03:59
1

Yes, you can do this, but not exactly the way you describe it now. Wherever you use Thread.sleep() you will have to catch InterruptedException, so you would have to enclose the call in the method like this:

public void trySleep(long ms) {
    try {
        Thread.sleep(ms);
    } catch (InterruptedException e) {
        e.printStackTrace(); //handle exception here
    }
}

You can call this method like this: trySleep(333)

It is sometimes better to just add a throws declaration to your method though or to re-throw a more meaningful exception, unless you know that this is the location where it makes most sense to catch the exception.

midor
  • 5,487
  • 2
  • 23
  • 52
0

You could wrap your sleeping code in another method as you sugested.

public static void trySleep(Thread target, long millis){
    try{
        target.sleep(millis);
    } catch(InterruptedException e) {
         System.err.println("Exception Occurred while trying to sleep!");
    }
}

You probably shoud do this, in fact, as making code modular is the right way to go.

ankh-morpork
  • 1,732
  • 1
  • 19
  • 28
  • The `target` parameter is redundant and misleading because [`Thread.sleep(...)`](http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#sleep%28long%29) is a static method that causes the _current_ thread to sleep. For readability's sake, static methods should not be called through instance references. – Mick Mnemonic Apr 05 '15 at 23:47
0

One important thing I think you really need to consider (in addition to the answers to how to do this properly), is to understand what code you're calling.

In your code:

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

Particularly this line:

trySleep(Thread.sleep(333));

You're basically saying

  • Call the method Thread.sleep() with a value of 333.

  • Whatever value Thread.sleep() returns, pass that to another method.

But the Javadocs say it's a void method.

Also in your code:

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

You should check this stackoverflow post out for why this is not good practice (as you'll be trying to invoke a static method on an instance object).

Others have answered your question on this, but I highly recommend brushing up on these areas as it indicates you may likely be missing critical knowledge of some important concepts.

Community
  • 1
  • 1
Water
  • 3,245
  • 3
  • 28
  • 58
0

You can use java 8's lambda expressions to do something similar to this:

@FunctionalInterface
interface InterruptedExceptionRunnable {
    void run() throws InterruptedException;
}

void trySleep(InterruptedExceptionRunnable exRunnable) {
    try {
        exRunnable.run();
    } catch(InterruptedException ex) {
        ex.printStackTrace();
    }
}

which allows you to write this:

trySleep(()->Thread.sleep(333));
fabian
  • 80,457
  • 12
  • 86
  • 114
0

Yes, you can do basically this with Java 8 lambdas.

class Example {
    @FunctionalInterface
    interface InterruptableRunnable {
        void run() throws InterruptedException;
    }

    static void tryRun(InterruptableRunnable r) {
        try {
            r.run();
        } catch(InterruptedException ie) {
            ie.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                // passing a lambda
                tryRun( () -> Thread.sleep(333) );
            }
        });

        t.start();
        // passing a method reference
        tryRun(t::join);
    }
}
Radiodef
  • 37,180
  • 14
  • 90
  • 125