问题描述
我正在尝试理解和使用异常。
为什么要用finally?而不是 finally 我也可以做一个 catch(Exception e){}。这样我的程序永远不会崩溃,并且总是执行 catch 之后的代码。 此外,我可以在 try 和 catch 之后添加一个 if/else 来检查是否抛出了异常。这样我的程序就永远不会崩溃,并且 if/else 会创建一个标准行为。
例如伪代码:
public void enterandPrintANumber() {
boolean exception = false;
int number = 0;
try {
System.out.println("Please enter a Number")
number = BufferedReader.readLine();
} catch(NumberFormatException e) {
System.out.println("Please enter a number")
}
catch(Exception e) {
System.out.println("An error has occurred")
exception = true;
}
if(exception) {
System.out.println("Action will be restarted")
this.enterandPrintANumber();
} else {
System.out.println("Your Number is "+number)
}
}
解决方法
简而言之,try/catch/finally 被解释为您想要尝试的代码,如果出现问题该怎么办,以及最后的清理代码。 finally 块最常见的用途是关闭已完成的资源。所以你可以有一个像:
Reader reader = null;
try {
reader = new StringReader("test");
//do stuff with reader
} catch (Exception e) {
//print the exception,log it,do something.
} finally {
reader.close()
}
现在,由于添加了可自动关闭 AutoClosable 界面的 Try With Resources 结构,此用例已大部分被弃用。
另一个用例是,如果您将信号量之类的东西用于同步目的。在您的 try{} 块中,您将获取 () 信号量,而在您的 finally 块中,您将释放它。
,好的..... 对于catch:catch 仅在执行代码时出现异常时才执行。这是为了使代码在意外情况下可用。您显然不希望以意外的方式崩溃和停止您的代码。
最后:假设您正在使用数据库。现在,无论是否发生崩溃,在完成必要的处理后关闭数据库连接确实是一个好习惯。另一个例子可能是文件系统。如果您正在处理文件并且是否发生崩溃,您可能总是希望在完成工作或处理后关闭文件流。你可能会问为什么?
嗯,这个答案解释得很好:https://stackoverflow.com/a/4111621/11928455
所以,无论是否发生崩溃,finally 都会被执行。在最后一个块中,您将以优雅的方式关闭与数据库、文件流...等的连接。