Please read the Embedefinally.java example before running it, observing its output and summarizing it.
Source:
public class Embededfinally {
public static void Main (String args[]) {
int result;
try {
System.out.println ("in Level 1");
try {
System.out.println ("in Level 2");
result=100/0; Level 2
try {
System.out.println ("in Level 3");
result=100/0; Level 3
}
catch (Exception e) {
System.out.println ("Level 3:" + E.getclass (). toString ());
}
finally {
System.out.println ("at level 3 finally");
}
result=100/0; Level 2
}
catch (Exception e) {
System.out.println ("Level 2:" + E.getclass (). toString ());
}
finally {
System.out.println ("at level 2 finally");
}
result = 100/0; Level 1
}
catch (Exception e) {
System.out.println ("Level 1:" + e.getclass (). toString ());
}
finally {
System.out.println ("at level 1 finally");
}
}
}
The Unlock method is written in the finally{} and executes the code in this case regardless of whether there is an exception.
public class Embededfinally {
public static void Main (String args[]) {
int result;
try {
System.out.println ("in Level 1");
try {
System.out.println ("in Level 2");
result=100/0; Level 2
try {
System.out.println ("in Level 3");
result=100/0; Level 3
}
catch (Exception e) {
System.out.println ("Level 3:" + E.getclass (). toString ());
}
finally {
System.out.println ("at level 3 finally");
}
result=100/0; Level 2
}
catch (Exception e) {
System.out.println ("Level 2:" + E.getclass (). toString ());
}
finally {
System.out.println ("at level 2 finally");
}
result = 100/0; Level 1
}
catch (Exception e) {
System.out.println ("Level 1:" + e.getclass (). toString ());
}
finally {
System.out.println ("at level 1 finally");
}
}
}
Summary:Java by using the try... Catch ... .. finally statement to catch one or more exceptions, Catch A statement can have one or more, and at least one Catch statement or finally . If an exception occurs somewhere, The code after this is not executed in the try statement, such as:
try{
String s= "ABC";
int I=integer.parseint (s);
int a=i+10;
}
When the program runs, the exception occurs, and the try statement throws an exception object,a=i+10; This statement is not executed after the exception occurs.
Finallystatement usage: Because when an exception occurs, the allocated resource remains in its original state and cannot be released, sofinallystatements are primarily used to release and clean up related resources or aftercare work, such as closing open files. Finallystatement is a unified export, that is, whetherTrystatement, and whether or not an exception occurred in theCatchThe exception type of the statementTrywhether the type of exception thrown by the statement matches,finallythe code in the statement is to be executed. Finallystatement is not required, and if you do not need to release resources in some situations,Try... ..CatchThe statement can have nofinallystatement.
Multiple nested try...catch...finally