抛出新的异常并有一个块来捕获任何异常

问题描述 投票:0回答:2
private WebElement findElementByXpath(WebDriver driver, String xpath) throws WebElementNotFoundException, HopelessAccountException {

    WebElement element = null;

    try {
        element = new WebDriverWait(driver, Duration.ofSeconds(dirationInSeconds))
                .until(ExpectedConditions.elementToBeClickable(By.xpath(xpath)));
    } catch (TimeoutException timeoutException) {
        loggingService.timeMark("findElementByXpath", "TimeoutException");
        throw new WebElementNotFoundException();
    } catch (UnhandledAlertException alertException) {
        loggingService.timeMark("findElementByXpath", "alertException");

        final String LIMITS_EXHAUSTED_MESSAGE = "Not enough limits!";
        String message = alertException.getMessage();

        if (message.contains(LIMITS_EXHAUSTED_MESSAGE)){
            throw new HopelessAccountException(); // Attention.
        }

    } catch (Exception e) {
        // Mustn't be here.
        loggingService.timeMark("findElementByXpath", e.getMessage());
        driver.quit();
        System.out.println("QUIT!");
        System.exit(0);
    }


    loggingService.timeMark("findElementByXpath", "end. Xpath: " + xpath);

    return element;
}

请参阅我评论为“注意”的那一行。

我发现了一个例外,即不再有足够的限制。我抛出了该帐户无望的异常。

但是在接下来的几行之后它立即被捕获。即我评论“一定不能在这里”的地方。

我想保留这个捕获任何异常的功能。至少用于调试目的。

我可以抛出 HopelessAccountException 并保留“catch Exception”块吗?

java
2个回答
2
投票

如果它是

Exception
的实例,您可以随时修改
e
块以重新抛出
HopelessAccountException

} catch (Exception e) {

    if (e instanceof HopelessAccountException) throw e;  // preserves original stack trace

    // Mustn't be here.
    loggingService.timeMark("findElementByXpath", e.getMessage());
    driver.quit();
    System.out.println("QUIT!");
    System.exit(0);
}

但是,正如 @fishinear 所指出的,在您发布的代码中,由于

Exception
的抛出,将无法到达
throw new HopelessAccountException()
块 - 如果您的实际代码看起来更像是:

try {
    try {
        System.out.println("In A()");
        // do something to cause an exception E3 (e.g. UnhandledAlertException)
        throw new E3();
    } catch (E3 e3) {  // UnhandledAlertException
        System.out.println("In E3 catch");
        throw new E1(); // HopelessAccountException
    }
} catch (Exception e) {
    System.out.println("In Exception catch");
    if (e instanceof E1) throw e; // rethrow HopelessAccountException
    System.out.println("e: "+e);
}

然后可以进行测试并重新抛出。

然后,当您删除调试“try 块”时,您的代码将表现相同(对于

HopelessAcountException
)。


0
投票

在调用 findElementByXpath(...) 的代码中,您可以捕获广泛的异常类型。这意味着在您的 findElementByXpath(...) 方法中,您可以只处理已知的异常,并且可以在调用代码中捕获其他任何内容

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