java 如何在Java主类中抛出多个异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4544014/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 06:52:36  来源:igfitidea点击:

How to throw multiple exceptions in Java main class

javaexception-handling

提问by Dream Lane

Will this work correctly (it compiles). Or is there a better way for me to throw multiple exceptions when calling the Java main() class?

这会正常工作吗(它编译)。或者有没有更好的方法让我在调用 Java main() 类时抛出多个异常?

public static void main(String[] args)
                         throws AWTException, IOException{}

回答by spaaarky21

Yes, that will work. But for future reference, if you find yourself throwing multiple exceptions that are similar and are recovered from in the same manner, see if they both inherit from the same parent exception other than java.lang.Exception. If so, you can throw that instead. You can always just throw Exception itself (and nothing else) but that brings up some best-practice issues.

是的,这会奏效。但是为了将来参考,如果您发现自己抛出了多个相似且以相同方式从中恢复的异常,请查看它们是否都继承自 java.lang.Exception 以外的同一个父异常。如果是这样,你可以把它扔掉。您总是可以只抛出 Exception 本身(而不是其他任何东西),但这会带来一些最佳实践问题。

回答by fastcodejava

Why don't write some code and test it, you are half way there. It looks fine. The method mainis not usually called by anyone. If that is case, there is no need to declare the throwsclause.

为什么不写一些代码并测试它,你已经成功了一半。看起来不错。该方法main通常不被任何人调用。如果是这种情况,则无需声明该throws子句。