You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在保留catch Exception块的同时抛出HopelessAccountException?

解决方法

问题根源在于HopelessAccountException属于Exception的子类,你在UnhandledAlertException分支抛出它后,会被后续兜底的catch(Exception e)块捕获,无法向上传递。要保留兜底调试逻辑同时让指定异常正常抛出,只需在通用catch块里过滤掉需要抛出的异常类型即可:

修改后的代码如下:

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) {
        // 先判断是否是我们需要抛出的异常类型
        if (e instanceof HopelessAccountException || e instanceof WebElementNotFoundException) {
            throw 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;
}

逻辑说明

  • 当兜底catch块捕获到异常时,先检查是否是我们声明要抛出的HopelessAccountException或WebElementNotFoundException,如果是就直接重新抛出,交给上层方法处理。
  • 只有遇到完全未预期的异常(比如其他RuntimeException或Error的子类),才执行退出逻辑,保留调试能力。

内容的提问来源于stack exchange,提问作者Kifsif

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 16:01:18