public class DemoApp {
public static void main(String[] args) {
System.out.println("start");
String val = "original";
try {
val = caller(); // remains "original"
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println(val); // "original"
}
public static String caller() throws Exception {
int x = 100;
int y = 0;
try {
System.out.print("before ");
int z = x / y;
return "success"; // skipped
} catch (Exception e) {
System.out.print("caught ");
throw new Exception("failure");
}
}
}
- The
throw inside catch terminates the method immediately; no further statements in that method execute. Omitting the final return is valid because the exception already exits the method.
- The division by zero occurs at
int z = x / y;. Code before this line runs normally, but the subseqeunt return is never reached. Flow jumps straight into the catch block.
- In
main, val = caller() never completes the assignment because caller() throws an exception. The variable val keeps its previous value "original".
public class DemoApp {
public static void main(String[] args) {
System.out.println("start");
String val = "original";
try {
val = handler(); // becomes "fallback"
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println(val); // "fallback"
}
public static String handler() throws Exception {
int x = 100;
int y = 0;
try {
System.out.print("before ");
int z = x / y;
return "success"; // skipped
} catch (Exception e) {
System.out.print("captured ");
}
return "fallback";
}
}
- If the
catch block does not rethrow or return, the method continues to the default return statement. The method must provide a return value on all paths; removing the final return causes a compilation error.
- Here
handler() completes successfully and returns "fallback". The variable val in main updates to "fallback".
- Since
handler() no longer throws an exception, the caller does not need a try-catch and can be simplified:
public class DemoApp {
public static void main(String[] args) {
System.out.println("start");
String val = "original";
val = handler(); // "fallback"
System.out.println(val); // "fallback"
}
public static String handler() {
int x = 100;
int y = 0;
try {
System.out.print("before ");
int z = x / y;
return "success";
} catch (Exception e) {
System.out.print("captured ");
}
return "fallback";
}
}