Whether or not a violation occurs in a try block, we often want to execute some specific code. This is often the case for certain operations, but it is not generally necessary to recover memory (because the garbage collector takes care of everything automatically). For this purpose, a finally clause (note ④) can be used at the end of all the offending controllers. So the complete violation control section looks like this:
try {
//area to defend:
//May "throw" out a,b, or C's dangerous situation
} catch (a A1) {
//controller A
} catch ( b B1) {
//controller B
catch (C C1) {
//controller C
} finally {
//Every time it happens
}
④:c++ violation control not provided finally clause, because it relies on the builder to achieve this cleanup effect.
to demonstrate the finally clause, test the following procedure:
: Finallyworks.java
//The FINALLY clause is always executed public
class Finallyworks {
static int count = 0;
public static void Main (string[] args {while
(true) {
try {
//post-increment is zero:
if (coun t++ = = 0)
throw new Exception ();
System.out.println ("No exception");
catch (Exception e) {
System.out.println ("Exception thrown");
} finally {
System.out.println ("in finally clause ");
if (count = = 2) break; Out of ' While '}}}
///:~
Through this procedure, we also know how to deal with the fact that the Java violation (such as C + +) does not allow us to revert to the place where the offence was created. If you place your try block into a loop, you can create a condition that must be satisfied before proceeding with the program. You can also add a static counter or some other device that allows the loop to try several different methods before discarding it. As a result, our programs can become more "robust".
The output is as follows:
Exception thrown in
finally clause
No Exception in
finally clause
Whether or not a violation is "thrown", the finally clause will be enforced.