try, catch, finally in return
Today in doing a multithreaded plus read and write lock test, consider the efficiency of the problem, want to return the results in time, but there is a serious problem, that is the lock on the open and closed. Because the lock is turned on, the end of use does not close in time, will be caused by the blockage of resources can not be requested. So, do a test, try to be comprehensive, even if some appear to have some brain residue, testing.
Example 1.
/**
* @author Qing
* * * try......catch......finally the return test/public
class Trytest {
/**
* Main Method
*
/public static void main (string[] args) {
//Call test method
String result = Get ();
Prints the results returned by the test method
System.out.println (result);
}
@SuppressWarnings ({"Finally", "unused"}) public
static String get () {
int value = 0;
try {
System.out.println ("Try ...");
Equation 1/0: The obvious error of denominator 0- -manufacturing error (for throwing exception)
int result = 1/value;
Return "a";
} catch (Exception e) {
System.out.println ("catch ...");
return "444";
} finally {
System.out.println ("finally ...");
return "333";
}
return "222";
}
Run Result:
After testing:
(1) After the check through the compiler, if finally there is return, then in the finally back, the other will be invalidated, the previous code is valid.
(2) The return "222" in line 37th is a catch, any return mutex in the finally. That is, there is a return in one of the catch and finally, and the compiler is able to check that it has complied with the returned requirements of the method.
(3) Catch and finally in, can exist at the same time return, compilation can pass. But the program with finally return "333" , will not ignore the catch return "444", catch in the code before return is still in force.
Example 2. (This is a better understanding)
There is no exception in the try interior of the program, if there is finally, and finally there is no return. If you encounter return in a try, first jump to execute the code in the finally, returning in the try.
Package threadproject;
/**
* @author Qing
* * * try......catch......finally the return test/public
class Trytest {
/**
* Main Method
*
/public static void main (string[] args) {
//Call test method
String result = Get ();
Prints the results returned by the test method
System.out.println (result);
}
public static String get () {
try {
System.out.println ("Try ...");
Return "a";
} catch (Exception e) {
System.out.println ("catch ...");
} finally {
System.out.println ("finally ...");
}
Return "222";
}
The results of the operation are:
The above program does not perform a try ... Return outside the catch......finally, that is, print "111", and not print "222".