是否可以将例外用作条件?

问题描述 投票:2回答:5

所以这里是我的应用程序的一些代码:

public void run() throws myException{
    boolean gameOver = false;
    while(!gameOver){
        //do stuff, and eventually make gameOver true to end execution
...

接下来是交易,我想删除布尔属性以使用用户定义的异常来结束执行。我正在考虑检查是否在while条件下抛出了这个异常,只要它没有被抛出就保持循环。

有点像

while(myException.notThrown){

可以这样做吗?

java exception condition
5个回答
3
投票

您的问题的答案是肯定的,但这种结构的实施取决于您的需求。

直接(和不恰当的)方式是:

public void run() {
    MyException ex = null;
    while(ex == null) {
        try {
            // Do stuff
        } catch(MyException e) {
            // Maybe handle this exception
            ex = e;
        }
    }
}

但这是一种奇怪的逻辑形式,可以简化为:

public void run() {
    while(true) {
        try {
            // Do stuff
        } catch(MyException e) {
            // Maybe handle this exception
            break;
        }
    }
}

或者这是我对这三者的偏好:

public void run() {
    try {
        while(true) {
            // Do stuff
        } 
    } catch(MyException e) {
       // Maybe handle this exception
    }
}

尽管存在所有这些可能性,因为你的throws MyException签名中已经有run,假设你的调用者正确处理它,你可以这样做:

public void run() throws MyException {
    while(true) { // Or maybe some exit condition?
        try {
            // Do stuff
        }
    }
}

这使异常传播给调用者。然后,让调用者处理生成的异常:

try {
    myObject.run();
} catch(MyException e) {
    // Handle this exception
}

您想要使用的结构取决于您的逻辑流程。考虑哪个实体应该处理您的自定义异常。抛出此异常是什么意思?谁/什么负责处理这种情况?


2
投票

但为什么?如果你真的需要它,你可以做一个无限循环来做它,你可以做那样的事情

while (true) {
    try {
        // some code to throw an exception
    } catch(Exception e) {
        e.printStackTrace();
        break;
    }
}

更新你可以将内循环变成异常

try {
    while (true) {
        // some code to throw an exception in order to remove the break keyword
    }
} catch (Exception e) {
    e.printStackTrace();
}

0
投票

Can this be done?

是的,你可以这样做:

public class Example {
    public static void run() throws IOException {
        if (Math.random() > 0.75) {
            throw new IOException();
        }
    }
    public static void main(final String... args) {
        boolean thrown = false;
        while (!thrown) {
            System.out.println("Roll");
            try {
                run();
            } catch (IOException ex) {
                thrown = true;
            }
        }
        System.out.println("Done");
    }
}

在示例卷上输出哪个:

Roll
Roll
Roll
Roll
Roll
Done

Should this be done

这可能是一个糟糕的想法,因为它会使代码更难阅读,更难维护,抛出异常的开销也可能使代码变慢。


0
投票

你可以在休息的同时使用无尽的时间。如果发生异常,你会打破。

while (true) {
    try {
        ...
    } catch (YourException e) {
        break;
    }
}

0
投票

对的,这是可能的。但是使用flow control is generally considered an anti-pattern的例外;它使得更难以阅读和调试代码。

© www.soinside.com 2019 - 2024. All rights reserved.