我在变量中有一个异常(没有抛出).
什么是最好的选择?
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(); }
Boann.. 9
我建议使用,instanceof
因为它可能会更快.抛出异常是一项复杂而昂贵的操作.在没有发生异常的情况下,JVM被优化为快速.例外应该是例外.
请注意,该throw
技术可能无法编译,如果您的异常类型是一个经过检查的异常,编译器会抱怨您必须捕获该类型或将其声明为抛出(else { ... }
如果您使用该instanceof
技术,则对应于一个子句),这可能或者可能没有帮助,具体取决于您希望如何处理不属于某个特定子类型的异常.