try在java中做什么?
try在java中做什么?,java,exception-handling,try-catch,Java,Exception Handling,Try Catch,try在java中做什么?try用于异常处理 您所说的是“尝试/抓住”块。它用于捕获“try/catch”中代码块内可能发生的异常。异常将在“catch”语句中处理。它允许您为代码块定义异常处理程序。将执行此代码,如果出现任何“异常”(空指针引用、I/O错误等),将调用相应的处理程序(如果已定义) 有关更多信息,请参阅wikipedia。它允许您尝试操作,并且在引发异常的情况下,您可以优雅地处理异常,而不是让异常冒泡并以丑陋且通常无法恢复的错误形式暴露给用户: try { int res
try
在java中做什么?try
用于异常处理
您所说的是“尝试/抓住”块。它用于捕获“try/catch”中代码块内可能发生的异常。异常将在“catch”语句中处理。它允许您为代码块定义异常处理程序。将执行此代码,如果出现任何“异常”(空指针引用、I/O错误等),将调用相应的处理程序(如果已定义)
有关更多信息,请参阅wikipedia。它允许您尝试操作,并且在引发异常的情况下,您可以优雅地处理异常,而不是让异常冒泡并以丑陋且通常无法恢复的错误形式暴露给用户:
try
{
int result = 10 / 0;
}
catch(ArithmeticException ae)
{
System.out.println("You can not divide by zero");
}
// operation continues here without crashing
try/catch/finally
构造允许您指定在try块内部发生异常时运行的代码(catch
),和/或在try块之后运行的代码,即使发生异常(finally
)
最后,块对于释放诸如数据库连接或文件句柄之类的资源非常重要。如果没有它们,您将无法可靠地在出现异常的情况下执行清理代码(或者在try块之外返回、中断、继续等等)
try
通常与catch
一起用于在运行时可能出错的代码,该事件称为引发异常。它用于指示机器尝试运行代码,并捕获发生的任何异常
因此,例如,如果您请求打开一个不存在的文件,该语言会警告您发生了错误(即,它被传递了一些错误的输入),并允许您通过将其包含在try..catch
块中来说明发生了什么
File file = null;
try {
// Attempt to create a file "foo" in the current directory.
file = File("foo");
file.createNewFile();
} catch (IOException e) {
// Alert the user an error has occured but has been averted.
e.printStackTrace();
}
在执行try..catch
块后,可以使用可选的finally
子句,以确保始终进行某些清理(如关闭文件):
File file = null;
try {
// Attempt to create a file "foo" in the current directory.
file = File("foo");
file.createNewFile();
} catch (IOException e) {
// Alert the user an error has occured but has been averted.
e.printStackTrace();
} finally {
// Close the file object, so as to free system resourses.
file.close();
}
异常处理没有尝试,只有Do以前没有问过吗?哦,别忘了googledo(尝试),还有(学习)或者(失败),你能更深入地解释为什么最终块是重要的吗?注意,“捕获”也是可选的。
File file = null;
try {
// Attempt to create a file "foo" in the current directory.
file = File("foo");
file.createNewFile();
} catch (IOException e) {
// Alert the user an error has occured but has been averted.
e.printStackTrace();
} finally {
// Close the file object, so as to free system resourses.
file.close();
}