英文:
Behavior of executing a method call with a checked exception at runtime without catching it
问题
假设我有一个叫做 A 的调用者类,它位于名为 a.jar 的 JAR 文件中,调用另一个单独的 JAR 文件 b.jar 中的方法 B.b()。
直到这一步,一切都正常。
现在 B 包的开发人员在 B.b() 中添加了一个已检查的异常,使得 B.b() 变成了像这样 B.b() throws Exception,并重新部署了 b.jar 文件。a.jar 文件保持不变,未经触碰,因此 A 包的开发人员没有注意到编译错误,需要立即捕获异常。
在运行时会发生什么?更准确地说,JVM 如何处理这种情况。根据我的经验,如果在运行时实际上没有抛出异常,那么情况会顺利进行。因此,似乎即使在异常级别上签名不匹配,方法解析也会执行。另一方面,如果 B.b() 实际上抛出异常,我不知道会发生什么。这种行为是否在 JVM 或 Java 语言规范的某处有明确说明,还是由 JVM 的实现者决定,甚至可以通过某些 JVM 标志选项进行配置?
谢谢您的解答。
英文:
Suppose I have caller Class named let's say A in a jar file a.jar that calls a method let say B.b() in a separate jar file b.jar.
Until there everything is ok.
Now B package developers are adding a checked Exception to B.b() which becomes something like B.b() throws Exception and redeploy the b.jar file. The a.jar file is kept intact, untouched so the A package developers do not notice the compile error requiring to catch the exception immediately.
What will happen at runtime ? More precisely how the JVM deals with that. From my experience, but surprisingly it works smoothly in the case where no exceptions are actually thrown at runtime. So it looks that the method resolution is performed even if signature does not match at the exception level. On the other hand, if B.b() actually throws an exception I have no idea of what will happen. Is this behaviour specified somewhere in the JVM or Java language specification or it is up to the JVM implementor or maybe even configurable with some JVM flags options ?
Thanks for your clarifications
答案1
得分: 2
异常不属于方法签名的一部分,至少不用于标识预期使用的方法。此外,在虚拟机级别上,并不存在所谓的“已检查异常”。您可以抛出任何喜欢的异常,即使您的方法签名没有声明它。您认为 Lombok 的 SneakyThrows 或者 Scala 是如何工作的呢?
英文:
Exceptions are not part of a method's signature, at least, for identifying which method is intended. Furthermore, at the VM level, there is no such thing as a 'checked exception'. You can throw anything you like, even if the signature of your method doesn't declare it. HOw do you think lombok's SneakyThrows, or scala works?
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论