gpt4 book ai didi

java - 为什么代码在 "return"之后仍在运行

转载 作者:行者123 更新时间:2023-12-01 16:57:13 25 4
gpt4 key购买 nike

我发现我的代码在点击“return table;”后仍在运行(我已经运行了 Debug模式,它确实前进到了下一行,怎么回事?一旦调用 return 语句,我的函数不应该立即结束(退出)吗?我的递归有问题吗?

public static HtmlTable getTableFromDomElement(DomElement element) throws Exception{

if(element instanceof com.gargoylesoftware.htmlunit.html.HtmlTable){
System.out.println("----YES!!!!-----");
HtmlTable table = (HtmlTable) element;
return table;
}

for(DomElement e : element.getChildElements()){
getTableFromDomElement(e);
}

throw new Exception("No HTML table found");
}

输出:

----是!!!-----

线程“main”java.lang.Exception中出现异常:未找到 HTML 表

最佳答案

找到后需要停止搜索,但不会停止 for 循环。相反,对于“未找到”的情况返回 null 并在第一次看到非 null 时返回:

public static HtmlTable getTableFromDomElement(DomElement element) throws Exception {
HtmlTable table;

if(element instanceof HtmlTable){
System.out.println("----YES!!!!-----");
table = (HtmlTable) element;
return table;
}

for(DomElement e : element.getChildElements()){
table = getTableFromDomElement(e);
if (table != null) {
return table;
}
}

return null;
}

(如果代码调用不再抛出异常,请删除抛出异常。)另请注意,因为您明确导入了com.gargoylesoftware.htmlunit.html(否则,您的 HtmlTable 返回类型声明将不起作用),您的 instanceof 中不需要 com.gargoylesoftware.htmlunit.html.HtmlTable查看。只需 HtmlTable 即可满足您的需求。

如果您需要一个在未找到时抛出异常的版本,则它必须是一个包装函数。

public static HtmlTable getTableFromDomElementOrThrow(DomElement element) throws Exception{
HtmlTable table = getTableFromDomElement(element);
if (table == null) {
throw new Exception("No HTML table found");
}
return table;
}

(嗯,它没有是一个包装函数,您可以在循环的每次迭代中捕获异常,但由于子元素不具有表并不是异常情况,这不是抛出异常的合适位置。在每次循环迭代中抛出异常也会明显降低效率。)

<小时/>

或者这是一个仅在一个地方返回的重构版本(有时被认为是良好实践):

public static HtmlTable getTableFromDomElement(DomElement element) throws Exception {
HtmlTable table = null;

if(element instanceof HtmlTable){
System.out.println("----YES!!!!-----");
table = (HtmlTable) element;
} else {
for (DomElement e : element.getChildElements()){
table = getTableFromDomElement(e);
if (table != null) {
break;
}
}
}

return table;
}

关于java - 为什么代码在 "return"之后仍在运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31101960/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com