1.try,catch,finally
The Try keyword is used to enclose logical code that may appear to be abnormal, which is not used alone and must be used with catch or finally. The Java compiler allows a combination of the following three forms:
Try...catch ...; Try....finally ...; Try....catch...finally ...
Of course the catch block can have multiple, note that the try block has only one, and the finally block is optional (but there can be at most one finally block).
Three blocks are executed in the order of try->catch->finally.
Of course, if no exception occurs, the catch block will not execute. However, the finally block is executed under any circumstances (it is very important to note that, in some cases, the action to dispose of the resource is placed in the finally block).
When there are multiple catch blocks, they are matched in the order of the catch blocks, and once the exception type is matched by a catch block, it does not match the catch block that follows.
When using try: Catch.. Finally block, be careful not to use return in the finally block, because return in finally overwrites the existing return value. Let's look at an example:
123456789101112131415161718192021222324252627282930 |
import
java.io.FileInputStream;
import
java.io.FileNotFoundException;
import
java.io.IOException;
public
class
Main {
public
static
void
main(String[] args) {
String str =
new
Main().openFile();
System.out.println(str);
}
public
String openFile() {
try
{
FileInputStream inputStream =
new
FileInputStream(
"d:/a.txt"
);
int
ch = inputStream.read();
System.out.println(
"aaa"
);
return
"step1"
;
}
catch
(FileNotFoundException e) {
System.out.println(
"file not found"
);
return
"step2"
;
}
catch
(IOException e) {
System.out.println(
"io exception"
);
return
"step3"
;
}
finally
{
System.out.println(
"finally block"
);
//return "finally";
}
}
}
|
The output of this program is:
As you can see, after filenotfoundexception occurs in a try block, it jumps to the first catch block, prints "file not found" information, assigns "Step2" to the return value, then executes the finally block, and returns the return value.
From this example, the finally block is executed regardless of whether the try block or catch block contains a return statement.
If you modify this program a little bit, the return statement comment in the finally block is removed and the result is:
The last print is "finally", and the return value is overwritten again.
So if the method has a return value, avoid using return in the Finally, which makes the program structure confusing.
Try,catch,finally