英文:
What is the difference between "throws Exception" and "throws IOException"
问题
throws Exception
和throws IOException
之间有什么区别?
两者都可以使用。那么,在它们之间的主要区别是什么?如果其中一个不存在会怎么样?
英文:
What is the difference between throws Exception
and throws IOException
?
Either of them works. So, what's the major difference in between them? What if one of them had not existed?
答案1
得分: 1
这个问题实际上涉及了Java异常机制的基础知识,但奇怪的是,在StackOverflow上我找不到完全相同的问题...
这些声明告诉编译器(以及程序员)一个方法可能会抛出哪些异常类型。
throws Exception
意味着一个方法可能会抛出任何Exception
(可以是Exception
实例本身,也可以是任何Exception
的子类型,包括IOException
)。
throws IOException
表示一个方法可能会抛出IOException
,但不会抛出例如SQLException
。
通常最好声明_具体的_异常,例如throws IOException, ParseException
,而不仅仅写throws Exception
。
英文:
This question is really about the basics of Java exception mechanism, but, strangely, I couldn't find an exact duplicate on StackOverflow...
These declarations tell the compiler (and the programmers) which type(s) of exceptions may be thrown by a method.
throws Exception
means that a method may throw any Exception
(either an Exception
instance directly, or any subtype of Exception
, including IOException
).
throws IOException
tells that a method may throw an IOException
, but not, for example, SQLException
.
It is usually a good practice to declare specific exceptions, e.g. throws IOException, ParseException
, instead of just writing throws Exception
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论