Java:可以缩短try/catch吗?

Java:可以缩短try/catch吗?,java,try-catch,thread-sleep,Java,Try Catch,Thread Sleep,例如: try { Thread.sleep(333); } catch (InterruptedException e) { e.printStackTrace(); } 我可以使用创建的方法,比如trySleep(Thread.sleep(333)),以某种方式使用上面的try/catch吗这将与最初的尝试完全相同 使用示例: public class Test implements Runnable { public Test()

例如:

try {
        Thread.sleep(333);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
我可以使用创建的方法,比如
trySleep(Thread.sleep(333)),以某种方式使用上面的try/catch吗这将与最初的尝试完全相同

使用示例:

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();
    }

}
当然上面的代码不会编译,这只是个问题


我想要这种东西的原因是因为我发现try/catch的东西太乱了,读起来很烦人。

我不明白这个问题。如果将这三行添加到trySleep方法主体中,就会得到一个方法,该方法将使线程休眠

所以答案是肯定的

顺便说一下:
你写了一个没完没了的睡眠循环

我不明白这个问题。如果将这三行添加到trySleep方法主体中,就会得到一个方法,该方法将使线程休眠

所以答案是肯定的

顺便说一下:
您编写了一个无休止的休眠循环

您可以将
Thread.sleep
包装在一个函数中,该函数将任何异常作为运行时异常(或任何未捕获的异常)重新抛出


您可以将
Thread.sleep
包装到一个函数中,该函数将任何异常作为运行时异常(或任何未捕获的异常)重新抛出


是的,你可以这样做,但不完全是你现在描述的方式。无论在何处使用
Thread.sleep()
都必须捕获
InterruptedException
,因此必须将调用包含在如下方法中:

public void trySleep(long ms) {
    try {
        Thread.sleep(ms);
    } catch (InterruptedException e) {
        e.printStackTrace(); //handle exception here
    }
}
您可以这样调用此方法:
trySleep(333)


不过,有时最好只在方法中添加一个throws声明,或者重新抛出一个更有意义的异常,除非您知道在这个位置捕获异常最有意义。

是的,您可以这样做,但不能完全按照您现在描述的方式。无论在何处使用
Thread.sleep()
都必须捕获
InterruptedException
,因此必须将调用包含在如下方法中:

public static void trySleep(long millis) {
    try {
        Thread.sleep(millis);
    } catch (InterruptedException e) {
        throw new RuntimeException("Interrupted during sleep", e);
    }
}
public void trySleep(long ms) {
    try {
        Thread.sleep(ms);
    } catch (InterruptedException e) {
        e.printStackTrace(); //handle exception here
    }
}
您可以这样调用此方法:
trySleep(333)


不过,有时最好只向方法中添加一个throws声明,或者重新抛出一个更有意义的异常,除非您知道在这个位置捕获异常最有意义。

您可以根据建议将休眠代码包装到另一个方法中

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

事实上,您可能应该这样做,因为将代码模块化是正确的方法。

您可以按照您的建议,用另一种方法包装您的休眠代码

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

<>你可能会这样做,事实上,让代码模块化是正确的方法。

一个重要的事情,我认为你真的需要考虑(除了如何正确地做这个问题的答案),就是了解你所调用的代码。 在代码中:

@Override
public void run() {
    while (true){
        System.out.println("Testing");
        trySleep(Thread.sleep(333));
    }
}
public void trySleep(/*Thread object*/){
    //Code for try/catch
}
特别是这一行:

trySleep(Thread.sleep(333));
你基本上是说

  • 调用值为333的Thread.sleep()方法

  • 不管Thread.sleep()返回什么值,都将其传递给另一个方法

但是说这是一个无效的方法

在您的代码中:

@Override
public void run() {
    while (true){
        System.out.println("Testing");
        trySleep(Thread.sleep(333));
    }
}
public void trySleep(/*Thread object*/){
    //Code for try/catch
}
您应该检查一下为什么这不是一个好的实践(因为您将尝试在实例对象上调用静态方法)


P>其他人已经回答了你的问题,但是我强烈建议对这些领域进行润色,因为这表明你可能忽略了一些重要概念的批判性知识。

我认为你真的需要考虑一个重要的问题(除了如何正确地处理这些问题之外)。就是理解你在调用什么代码

在代码中:

@Override
public void run() {
    while (true){
        System.out.println("Testing");
        trySleep(Thread.sleep(333));
    }
}
public void trySleep(/*Thread object*/){
    //Code for try/catch
}
特别是这一行:

trySleep(Thread.sleep(333));
你基本上是说

  • 调用值为333的Thread.sleep()方法

  • 不管Thread.sleep()返回什么值,都将其传递给另一个方法

但是说这是一个无效的方法

在您的代码中:

@Override
public void run() {
    while (true){
        System.out.println("Testing");
        trySleep(Thread.sleep(333));
    }
}
public void trySleep(/*Thread object*/){
    //Code for try/catch
}
您应该检查一下为什么这不是一个好的实践(因为您将尝试在实例对象上调用静态方法)


其他人已经回答了您的问题,但我强烈建议您重新学习这些方面,因为这表明您可能缺少一些重要概念的关键知识。

您可以使用java 8的lambda表达式执行类似的操作:

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

void trySleep(InterruptedExceptionRunnable exRunnable) {
    try {
        exRunnable.run();
    } catch(InterruptedException ex) {
        ex.printStackTrace();
    }
}
这允许您编写以下内容:

trySleep(()->Thread.sleep(333));

您可以使用java 8的lambda表达式执行类似的操作:

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

void trySleep(InterruptedExceptionRunnable exRunnable) {
    try {
        exRunnable.run();
    } catch(InterruptedException ex) {
        ex.printStackTrace();
    }
}
这允许您编写以下内容:

trySleep(()->Thread.sleep(333));

是的,您基本上可以用Java8Lambdas实现这一点

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);
    }
}

是的,您基本上可以用Java8Lambdas实现这一点

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);
    }
}

你不内联此语句的原因是什么?你不内联此语句的原因是什么?我一直认为Thread.sleep必须在它运行的线程中?例如,如果您在construtor
Test()
中调用它,它将不起作用。@FOD当您从
run
内部调用
trySleep
时,您正在当前线程中调用它。函数定义在哪里并不重要。我一直认为Thread.sleep必须在它运行的线程中?例如,如果您在construtor
Test()
中调用它,它将不起作用。@FOD当您从
run
内部调用
trySleep
时,您正在当前线程中调用它。函数定义在哪里并不重要。我知道它是无止境的,这只是我选择制作的一个快速示例,示例中的任何其他内容都是毫无意义和无关的。这并不能回答这个问题。要评论或要求作者澄清,请在他们的帖子下方留下评论。@HarshalPatil:答案是“如果你在trySleep方法中添加了三行内容”。我对这个问题有一些问题,因为答案包含在问题中。哦,我认为这只是评论,我知道这是无止境的,这只是我选择做的一个简单的例子,例子中的任何其他内容都是毫无意义和无关的。这并不能提供问题的答案。批评或要求澄清