1)try中代码执行并返回:
public class TryCatchFinally {
public static void main(String[] args){
System.out.println("return value of x:=" + inc());
}
public static int inc() {
int x;
try{
//normal process
System.out.println("normal process");
x=1;
return x;
}catch(Exception e){
//Exception Process
System.out.println("Catch Process");
x=2;
return x;
}finally{
//process that catch process can not be trigger
x=3;
System.out.println("Fianlly and x : =" + x);
}
}
}
返回结果:
normal process
Fianlly and x : =3
return value of x:=1
2)执行Catch中代码并返回
public static void main(String[] args) {
System.out.println("return value of x:=" + inc());
}
public static int inc() {
int x;
try {
// normal process
System.out.println("normal process");
x = 1;
throw new Exception("error");
} catch (Exception e) {
// Exception Process
System.out.println("Catch Process");
x = 2;
return x;
} finally {
// process that catch process can not be trigger
x = 3;
System.out.println("Fianlly and x : =" + x);
}
}
执行结果:
normal process
Catch Process
Fianlly and x : =3
return value of x:=2
3)抛出异常,不执行catch块,直接执行finally快
public static void main(String[] args) throws Exception {
System.out.println("return value of x:=" + inc());
}
public static int inc() throws Exception {
int x;
try {
// normal process
System.out.println("normal process");
x = 1;
throw new Exception("error");
} catch (RuntimeException e) {
// Exception Process
System.out.println("Catch Process");
x = 2;
return x;
} finally {
// process that catch process can not be trigger
x = 3;
System.out.println("Fianlly and x : =" + x);
}
}
结果:
normal process
Exception in thread "main" Fianlly and x : =3
java.lang.Exception: error
at ClassStructure.TryCatchFinally.inc(TryCatchFinally.java:16)
at ClassStructure.TryCatchFinally.main(TryCatchFinally.java:6)
4)try-catch-finally执行之后x的值是多少
package ClassStructure;
public class TryCatchFinally {
private static int x;
public static void main(String[] args) {
System.out.println("return value of x:=" + inc());
System.out.println("process the method x : " + x);
}
public static int inc() {
// int x;
try {
// normal process
System.out.println("normal process");
x = 1;
return x;
} catch (RuntimeException e) {
// Exception Process
System.out.println("Catch Process");
x = 2;
return x;
} finally {
// process that catch process can not be trigger
x = 3;
System.out.println("Fianlly and x : =" + x);
}
}
}
执行结果:
normal process
Fianlly and x : =3
return value of x:=1
process the method x : 3