我正在尝试了解 Java 中的已检查异常并进行以下查询。
以下是否正确:如果方法有可能引发任何类型的已检查异常,则该异常必须是
- 使用
throws
关键字声明,或 - 被相应的方法捕获。
如果以上是正确的,这是否意味着我需要了解 Java 内置的每个已检查异常,以便我知道我的方法是否有可能引发该异常?还是我应该尝试编译我的代码,然后根据编译时错误修改我的代码?
If the above is correct, does this mean that I need to understand every single checked exception that is built in to Java [...]?
Yes, your statements are correct, but no one expects you to know of all potential checked exceptions when programming. And you don't have to if you have a compiler, or better, an IDE at hand.
Either you go back and forth between compiler output and code as you suggest in your question, or you install an IDE such as Eclipse which gives you direct notifications if you violate the rule:
does this mean that I need to understand every single checked exception that is built in to Java
I assume you are using some IDE (eg. Eclipse) - if not, you should get one ASAP.
Then, the IDE pretty much continuously compiles the code, so when there's a problem, you will get a red underline near it, and a tooltip bubble telling you what's wrong - eg "Missing throws".
Therefore, your second assumption is basically correct, it just happens behind the scenes:
Or should I just attempt to compile my code and then amend my code based on the compile-time errors?
So no, you don't need to learn all the exceptions.
Also, all checked Exceptions extend Exception
, so if you have access to the source, you can check what they are based on. Non-checked exceptions extend RuntimeException
.
Rule of thumb: If it's something with I/O, it's usually checked. That's the most common type of exception you will encounter.
whenever you use a method (whether your own or In-built) if you closely follow its method signature, if the method throws some exception you need to throw/handle it explicitly in your code
In this way you will not need to memorize all the exceptions and you will know which exceptions to handle where.
To make life easy use some IDE like eclipse
hope this helps!
Good luck!
是的,您需要知道每个异常..但是,如果您知道该异常的超类而不是您不需要知道它的子类...例如,FileReader 会抛出一个名为 FileNotFoundException 的异常,因为 FileNotFoundException 是 IOException 的子类,我们可以在 throws 列表中指定 IOException 并使上述程序无编译错误。
如果以上是正确的
这是...
[...] 这是否意味着我需要了解 Java 内置的每个已检查异常,以便我知道我的方法是否有可能生成该异常?还是我应该尝试编译我的代码,然后根据编译时错误修改我的代码?
使用 IDE!您不需要完全了解所有这些。
但是,您要检查的是层次结构(即检查 javadoc!这应该是巴甫洛夫反射);由于异常是类,它们相互继承,例如,FileSystemException
它是 java.nio.file 的一个 portmanteau 异常,用于表示与文件系统相关的问题,它继承了IOException
. IOException
如果您想特殊对待它,请先抓住它。
作为一般规则,首先捕获更具体的异常。
另外,不要抓住Exception
. 绝不。问题是RuntimeException
,它是未检查异常的基本异常,继承Exception
了,这意味着如果您捕获,Exception
您将捕获所有未检查异常。你想重新抛出未选中的:
try {
something();
} catch (RuntimeException unchecked) {
throw unchecked;
} catch (Exception e) {
// deal with e
}