public static void main(String[] args) { int test = test(3, 5); System.out.println(test);}public static int test(int x, int y) { int result = x; try { if(x < 0 || y < 0){ return 0; } result = x + y; return result; } finally { result = x - y; }}
public class Exercise4 { static int i = 0; public static void main(String[] args) { System.out.println(test()); } public static int test() { try { return ++i; } finally { return ++i; } }}
答案
2
catch 匹配顺序
import java.io.IOException;public class Exercise5 { public static void main(String[] args) { int a = -1; try { if (a > 0) { throw new RuntimeException(""); } else if (a < 0) { throw new IOException(""); } else { return; } } catch (IOException ioe) { System.out.println("IOException"); } catch (Throwable e) { System.out.println("Throwable"); } finally { System.out.println("finally"); } }}
答案
IOExceptionfinally
catch 是多分支结构,从上到下按顺序匹配,只会进入第一个匹配上的 catch 分支
catch 声明顺序
import java.io.IOException;public class Exercise5 { public static void main(String[] args) { int a = -1; try { if (a > 0) { throw new RuntimeException(""); } else if (a < 0) { throw new IOException(""); } else { return; } } catch (Throwable e) { System.out.println("Throwable"); } catch (IOException ioe) { System.out.println("IOException"); } finally { System.out.println("finally"); } }}
答案
Exercise5.java:16: error: exception IOException has already been caught } catch (IOException ioe) {^1 error
catch 如果有“包含”关系,声明从上到下必须是先“特”后“泛”
try-catch-finally 执行顺序
public class Exercise6 { public static int fun() { int result = 5; try { result = result / 0; return result; } catch (Exception e) { System.out.println("Exception"); result = -1; return result; } finally { result = 10; System.out.println("I am in finally."); } } public static void main(String[] args) { int x = fun(); System.out.println(x); }}
答案
ExceptionI am in finally.-1
throws
public class Exercise7 { public static int aMethod(int i) throws Exception { try { return 10 / i; } catch (Exception ex) { throw new Exception("exception in aMethod"); } finally { System.out.println("finally"); } } public static void main(String[] args) { try { aMethod(0); } catch (Exception e) { System.out.println("exception in main"); } }}