package Text01;
class Exercise {
public static String catchMethod() {
System.out.print("call catchMethod and return --->> ");
return "catchMethod";
} // finally后续处理工作
public static String finallyMethod() {
System.out.println();
System.out.print("call finallyMethod and do something --->> ");
return "finallyMethod";
}
public static String catchTest() {
try {
int i = 10 / 0; // 抛出 Exception,后续处理被拒绝
System.out.println("i vaule is : " + i);
return "Test"; // Exception 已经抛出,没有获得被执行的机会
} catch (Exception e) {
System.out.println(" -- Exception --");
return catchMethod(); // Exception 抛出,获得了调用方法并返回方法值的机会
}
}
public static String catchFinallyTest1() {
try {
int i = 10 / 0; // 抛出 Exception,后续处理被拒绝
System.out.println("i vaule is : " + i);
return "Test"; // Exception 已经抛出,没有获得被执行的机会
} catch (Exception e) {
System.out.println(" -- Exception --");
return catchMethod(); // Exception 抛出,获得了调用方法的机会,但方法值在 finally
// 执行完后才返回
} finally {
return finallyMethod(); // Exception 抛出,finally 代码块将在 catch 执行
// return 之前被执行
}
}
public static String catchFinallyTest2() {
try {
int i = 10 / 2; // 不抛出 Exception
System.out.println("i vaule is : " + i);
return "Test"; // 获得被执行的机会,但执行需要在 finally 执行完成之后才能被执行
} catch (Exception e) {
System.out.println(" -- Exception --");
return catchMethod();
} finally {
finallyMethod();
// return "finally"; // finally 中含有 return 语句,这个 return
// 将结束这个方法,不会在执行完之后再跳回
// try 或 catch 继续执行,方法到此结束,返回 false
}
}
public static String catchFinallyTest3() {
try {
int i = 10 / 2; // 不抛出 Exception
System.out.println("i vaule is : " + i);
return "Test"; // 获得被执行的机会,但执行需要在 finally 执行完成之后才能被执行
} catch (Exception e) {
System.out.println(" -- Exception --");
return catchMethod();
} finally {
finallyMethod();
// System.exit(0);
return "finally"; // finally 中含有 return 语句,这个 return
// 将结束这个方法,不会在执行完之后再跳回
// try 或 catch 继续执行,方法到此结束,返回 false
}
}
public static String catchFinallyTest4() {
try {
int i = 10 / 0; // 不抛出 Exception
System.out.println("i vaule is : " + i);
return "Test"; // 获得被执行的机会,但执行需要在 finally 执行完成之后才能被执行
} catch (Exception e) {
System.out.println(" -- Exception --");
return catchMethod();
}
}
public static void main(String[] args) {
// Cout.addLine("0---------"+catchTest());Cout.endl();
// Cout.addLine("1---------"+catchFinallyTest1());Cout.endl();//我这里使用了一个自定义的包,你们可以把它们全部变成System.out.println()语句
// Cout.addLine("2---------"+catchFinallyTest2());Cout.endl();
Cout.addLine("3---------"+catchFinallyTest3());Cout.endl();
Cout.addLine("4---------"+catchFinallyTest4());Cout.endl();
}
}
看完了你们可以试下变下程序,这个还是自己去实践才是最好的收获。
-- Exception --
call catchMethod and return --->> 0---------catchMethod
-- Exception --
call catchMethod and return --->>
call finallyMethod and do something --->> 1---------finallyMethod
i vaule is : 5
call finallyMethod and do something --->> 2---------Test
i vaule is : 5
call finallyMethod and do something --->> 3---------finally
-- Exception --
call catchMethod and return --->> 4---------catchMethod
看到了这个应该就懂了吧!!!