在 Java 的 try 语句中应该使用什么样的括号?
What kind of brackets should I use in try statements in Java?
我稍微阅读了 Oracle Java 文档,注意到他们在 try-Statements 中使用了“(”括号,但几乎所有人都只使用“{”。
是否存在优先于另一个的不同情况,或者它们之间没有区别?我在 Java API 中找不到答案所以我想为什么不在这里问...
Java中有两个不同的语句:try
和try-with-resources
。他们做相关但不同的事情。您将 {}
与 try
和 ()
以及 {}
与 try-with-resources
一起使用。 try-with-resources
使 显着 更容易使用支持 AutoCloseable
接口的资源,因为它会为您处理关闭资源(无论控件如何离开块——是否正常完成或抛出异常)。
示例 try
语句:
try {
// Do something that may throw an exception
}
catch (RelevantExceptionType e) {
// Do something about it
}
finally {
// This runs whether an exception happened or not
}
try
可以有零个或多个 catch
块和零个或一个 finally
块(并且必须至少有一个 catch
或 finally
, 它不能完全独立)。
this tutorial 中的更多内容。
样本try-with-resources
:
try (
InputStream is = new FileInputStream("some file")
) {
}
catch (RelevantExceptionType e) {
// Do something about it
}
finally {
// This runs regardless of whether there was an exception
}
try-with-resources
可以有零个或多个catch
块和零个或一个finally
块,没有要么(它可以完全独立)。
this tutorial 中的更多内容。
我稍微阅读了 Oracle Java 文档,注意到他们在 try-Statements 中使用了“(”括号,但几乎所有人都只使用“{”。
是否存在优先于另一个的不同情况,或者它们之间没有区别?我在 Java API 中找不到答案所以我想为什么不在这里问...
Java中有两个不同的语句:try
和try-with-resources
。他们做相关但不同的事情。您将 {}
与 try
和 ()
以及 {}
与 try-with-resources
一起使用。 try-with-resources
使 显着 更容易使用支持 AutoCloseable
接口的资源,因为它会为您处理关闭资源(无论控件如何离开块——是否正常完成或抛出异常)。
示例 try
语句:
try {
// Do something that may throw an exception
}
catch (RelevantExceptionType e) {
// Do something about it
}
finally {
// This runs whether an exception happened or not
}
try
可以有零个或多个 catch
块和零个或一个 finally
块(并且必须至少有一个 catch
或 finally
, 它不能完全独立)。
this tutorial 中的更多内容。
样本try-with-resources
:
try (
InputStream is = new FileInputStream("some file")
) {
}
catch (RelevantExceptionType e) {
// Do something about it
}
finally {
// This runs regardless of whether there was an exception
}
try-with-resources
可以有零个或多个catch
块和零个或一个finally
块,没有要么(它可以完全独立)。
this tutorial 中的更多内容。