英文:
Exception(checked and unchecked)
问题
有两种类型的异常,分别是已检查异常和未检查异常。已检查异常被定义为在编译时发生的异常,而未检查异常是在运行时捕获的异常。通常情况下,异常总是在运行时被捕获。那么,已检查异常如何在编译时被捕获呢?
英文:
There are 2 types of exceptions. Checked and unchecked. Checked is defined as an exception that occurs at compile time and unchecked is an exception caught at runtime. Usually an exception is always caught at runtime. So how is it possible that checked exception is caught at compile time.
答案1
得分: 1
那么,为什么编译时可以捕获已检查异常呢?
编译器可以检查被调用的方法或构造函数是否已被声明为会抛出已检查异常,这是编译器在编译时可获得的信息。有了这些信息,编译器可以检查调用代码是否抛出或捕获了异常,如果未发生这种情况,编译器会产生错误。
需要注意的是,异常可能会被抛出,也可能不会,在运行时才确定。因此,异常只有在运行时真正得到完全处理,如果它发生了的话。
英文:
> So how is it possible that checked exception is caught at compile time.
The compiler can check if the method or constructor that is being called has been declared to throw a checked exception which is information that is available to the compiler at compile time. With this information, the compiler can check to see if the calling code either throws or catches the exception and then give an error if this is not occurring.
Note that the exception may or may not be thrown, but only during run-time, and so it is only truly fully handled at run-time, if it occurs.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论