“throws Exception” 和 “throws IOException” 之间的区别是什么?

huangapple go评论77阅读模式
英文:

What is the difference between "throws Exception" and "throws IOException"

问题

throws Exceptionthrows 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.

huangapple
  • 本文由 发表于 2020年10月26日 02:29:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/64527305.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定