[英]Should you catch all exceptions in your main method
Is it correct to catch everything into the main? 将所有内容都纳入主体是否正确? If not, why? 如果没有,为什么?
public static void main(String[] args) {
try {
// A lot
// of
// calls
} catch (Exception e) {
e.printStackTrace();
}
}
Generally it's better to separate out the catches IMO, so that you can handle each separately even if you end up handling these the same. 通常,最好将IMO的渔获物分开,这样即使您最终以相同的方式进行处理,也可以将它们分别处理。 It's also easier to see what the risks are, what the catch is, when you come back to your code. 当您回到代码中时,也更容易看到风险是什么, 抓住了什么。 Just a quick example: 只是一个简单的例子:
try {
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (IOException e) {
request.abort();
} finally {
client.close();
}
If all you do is call e.printStacktrace ()
, I do not think it is worthwhile. 如果您只需要调用e.printStacktrace ()
,我认为这是不值得的。 The JVM will do something like that anyway. 无论如何,JVM都会做类似的事情。 But I believe it is worthwhile if you output a meaningful message; 但是,我认为如果您输出有意义的信息是值得的。 stacktraces are meaningful only to programmers. stacktrace仅对程序员有意义。
它会捕获try{}
块中的每个Exception
,如果内部代码中还有另一个catch捕获,则可能不会捕获
It depends. 这取决于。 If you only need to show some error messages when an exception arise, I guess it's ok. 如果您仅需要在出现异常时显示一些错误消息,我想就可以了。 But if you find the need to make some kind of processing depending on the type of exception, then you'll be better off try-catching in the inner code. 但是,如果您发现需要根据异常类型进行某种处理,那么最好尝试在内部代码中进行捕获。
In your case it makes no sense since you do not process the exception you catch but simply print it. 在您的情况下,这是没有意义的,因为您不处理捕获的异常,而只是将其打印出来。 If you declare main throws checked_exceptions_your_code_throws_list
you will get the same result (JVM will print exception) and a cleaner code. 如果声明main throws checked_exceptions_your_code_throws_list
,则会得到相同的结果(JVM将打印异常)和更干净的代码。 And if your code throws no checked exception then do not declare any exceptions at all. 而且,如果您的代码未引发任何检查异常,则根本不要声明任何异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.