为什么要在类定义中写入throws异常? [英] Why do you have to write throws exception in a class definition?
问题描述
来自C#,
我只是不知道在类/方法定义之后写的throws exception:
Coming from C#, I just don't get this 'throws exception' that is written after a class/method definition:
public void Test() throws Exception
你必须写这个吗?
如果没有,怎么办?
如果我调用一个有这个符号的方法,我必须抓住它吗?
Do you have to write this? What if you don't? If I call a method that has this symbol, do I have to catch it?
推荐答案
你不有在所有情况下写入 - 只要您的方法抛出一个检查的异常
(一个例外是异常
而不是 RuntimeException
的子类)。这是因为你的方法签名是一个合同,它声明所有的代码,它调用它有可能抛出给定的异常。因为它是一个检查的异常 - 一个可以预期的异常 - 调用代码需要预测看到抛出异常的可能性,需要能够处理它。
You don't have to write it in all cases -- you just have to write it if your method throws a checked Exception
(an exception that is a subclass of Exception
and not a subclass of RuntimeException
). This is because your method signature is a contract, and it's declaring to all the code which calls it that it has the potential for throwing the given exception. Because it's a checked exception -- an exception which can be anticipated -- the calling code needs to anticipate the potential of seeing the exception thrown, and needs to be able to handle it.
要回答您的两个具体问题:
To answer your two specific questions:
- 你必须写它/如果你不这样做:如果你的方法抛出一个检查的异常,那么是的,你必须在你的方法签名中声明它。如果你没有,那么你的代码将不会被编译。
- 你必须抓住它:你必须用它执行某些。调用该方法的代码可以捕获它并处理它,它可以捕获它并重新抛出它,或者它可以将其传递给链。为了传递链,代码调用该方法必须自己声明它引发相同的异常 - 例如,如果方法
bar
可以抛出$ code> SomeException 和方法foo
调用bar
并且不想抓住例外,foo
的方法签名将声明它也会抛出SomeException
。
- do you have to write it/what if you don't: if your method throws a checked exception, then yes, you have to declare it in your method signature. If you don't, then your code won't compile.
- do you have to catch it: you have to do something with it. The code calling the method can either catch it and handle it, it can catch it and re-throw it, or it can just pass it up the chain. In order to pass it up the chain, the code calling the method has to itself declare that it throws the same exception -- e.g., if method
bar
can throwSomeException
, and methodfoo
callsbar
and doesn't want to catch the exception, the method signature forfoo
would declare that it too throwsSomeException
.
例外章节Java课程非常擅长于此详细解释,而 JavaWorld有一篇关于抛出和捕获异常的好文章,我一直发现这是一个很好的参考,以传递给人们。
The Exceptions chapter of the Java lessons is very good at explaining this in detail, and JavaWorld has a good article about throwing and catching exceptions that I've always found to be a good reference to pass onto folks.
这篇关于为什么要在类定义中写入throws异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!