为什么 Java 不允许从静态初始化块中抛出已检查的异常? [英] Why doesn't Java allow to throw a checked exception from static initialization block?

查看:27
本文介绍了为什么 Java 不允许从静态初始化块中抛出已检查的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 Java 不允许从静态初始化块中抛出已检查的异常?这个设计决定背后的原因是什么?

Why doesn't Java allow to throw a checked exception from a static initialization block? What was the reason behind this design decision?

推荐答案

因为无法在您的源中处理这些已检查的异常.您无法控制初始化过程,并且无法从源中调用静态块,因此您可以使用 try-catch 包围它们.

Because it is not possible to handle these checked exceptions in your source. You do not have any control over the initialization process and static{} blocks cannot be called from your source so that you could surround them with try-catch.

由于您无法处理已检查异常指示的任何错误,因此决定禁止抛出已检查异常静态块.

Because you cannot handle any error indicated by a checked exception, it was decided to disallow throwing of checked exceptions static blocks.

静态块不得抛出已检查异常,但仍允许抛出未检查/运行时异常.但根据上述原因,您也无法处理这些.

The static block must not throw checked exceptions but still allows unchecked/runtime-exceptions to be thrown. But according to above reasons you would be unable to handle these either.

总而言之,此限制阻止(或至少使开发人员更难)构建可能导致应用程序无法从中恢复的错误的内容.

To summarize, this restriction prevents (or at least makes it harder for) the developer from building something which can result in errors from which the application would be unable to recover.

这篇关于为什么 Java 不允许从静态初始化块中抛出已检查的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆