A common way to use catch and finally is to get and use resources in a try block, handle exceptions in a catch block, and in the finally Frees resources in the block.
finally blocks are used to clean up any resources allocated by the try block, regardless of whether the try is abnormal or terminating (return), and thefinally block executes .
If the return value is modified in the finally block, what effect does it have on the results returned?
1, if the return value is a value type
//finally executes, I value is 2013, but finally returnsStatic intTest () {inti = .; Try{i= -; returni; } Catch{//There is an exception to be here i=2014;
return i; } finally{i= -; } }
2, returns the string type, whether it will affect it, the answer is not affected.
// finally block executes, s value is "Tiger", but eventually returns to dog static string Test () { string s = " cat " try {s = " dog " return S; catch {
There's an anomaly to be here.
S= "Duck";
return s;
} finally { s="Tiger"; } }
3, what happens when I return an array?
//finally block execution, which affects the final return result, returns {"E", "B", "C"};Static string[] Test () {string[] arr = {"a","b","C" }; Try{arr[0]="D"; returnarr; } Catch{//There is an exception to be here arr[0]= "F";
return arr; } finally{arr[0]="e";; } }
4, the object, like an array, finally modifies the object and eventually returns the finally modified object.
Attention:
1,finally Block cannot have return statement, of course, vs will error.
2, if there is a return statement after the finally block, how do I return it? i.e. try{}catch () {} finally{} return x;
The finally block is definitely executed, where the try and catch are mainly seen if the return statement is executed, and if executed, the statement after the finally block is not executed.
Of course, if both the try and catch blocks contain a return statement, then one will be executed, and the statement after the finally block will not execute, which is the VS will prompt "The code that is not accessible is detected".
Example
//return "dog", adding an exception will return "Duck",Static stringTest () {strings ="Cat"; Try{s="Dog"; returns; } Catch { //There's an anomaly to be here .s="Duck"; } finally{s="Tiger"; } returnS//If try returns correctly,Will not be executed. }
The effect of try-catch-finally on the return value