gpt4 book ai didi

java - 抛出并捕获异常,还是使用instanceof?

转载 作者:IT老高 更新时间:2023-10-28 20:53:24 25 4
gpt4 key购买 nike

我在变量中有异常(未抛出)。

最好的选择是什么?

Exception exception = someObj.getExcp();
try {
throw exception;
} catch (ExceptionExample1 e) {
e.getSomeCustomViolations();
} catch (ExceptionExample2 e) {
e.getSomeOtherCustomViolations();
}

Exception exception = someObj.getExcp();
if (exception instanceof ExceptionExample1) {
exception.getSomeCustomViolations();
} else if (exception instanceof ExceptionExample2) {
exception.getSomeOtherCustomViolations();
}

最佳答案

我建议使用 instanceof 因为它可能会更快。抛出异常是一项复杂且昂贵的操作。 JVM 进行了优化,以在发生异常的情况下快速运行。异常(exception)应该是异常(exception)。

请注意,throw 技术可能不会如图所示编译,如果您的异常类型是已检查异常,编译器会提示您必须捕获该类型或将其声明为已抛出(对应于else { ... } 子句(如果您使用 instanceof 技术),这可能有帮助也可能没有帮助,具体取决于您希望如何处理不是一个的异常具体的子类型。

关于java - 抛出并捕获异常,还是使用instanceof?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20431614/

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