import com.sun.net.httpserver.HttpServer;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
public class ExploreExceptionHandling {
public static void main(String[] args) throws Exception {
List<Map<String, Object>> cases = new ArrayList<>();
// Case 1: Checked vs Unchecked vs Error hierarchy & all 6 Throwable methods
FileNotFoundException checkedRoot = new FileNotFoundException("missing-config.xml");
RuntimeException wrapped = new RuntimeException("Error condition!!!", checkedRoot);
StringWriter traceBuf = new StringWriter();
wrapped.printStackTrace(new PrintWriter(traceBuf));
StackTraceElement[] frames = wrapped.getStackTrace();
Throwable refilled = wrapped.fillInStackTrace();
Map<String, Object> thExp = new LinkedHashMap<>();
thExp.put("checked_is_not_runtime", true);
thExp.put("runtime_is_exception", true);
thExp.put("stackoverflow_is_error", true);
thExp.put("get_message", "Error condition!!!");
thExp.put("get_cause_class", "java.io.FileNotFoundException");
thExp.put("to_string", "java.lang.RuntimeException: Error condition!!!");
thExp.put("print_stack_trace_has_class", true);
thExp.put("get_stack_trace_non_empty", true);
thExp.put("fill_in_returns_self", true);
Map<String, Object> thAct = new LinkedHashMap<>();
thAct.put("checked_is_not_runtime", Exception.class.isAssignableFrom(FileNotFoundException.class)
&& !RuntimeException.class.isAssignableFrom(FileNotFoundException.class));
thAct.put("runtime_is_exception", Exception.class.isAssignableFrom(RuntimeException.class));
thAct.put("stackoverflow_is_error", Error.class.isAssignableFrom(StackOverflowError.class));
thAct.put("get_message", wrapped.getMessage());
thAct.put("get_cause_class", wrapped.getCause().getClass().getName());
thAct.put("to_string", wrapped.toString());
thAct.put("print_stack_trace_has_class", traceBuf.toString().contains("java.lang.RuntimeException: Error condition!!!"));
thAct.put("get_stack_trace_non_empty", frames.length > 0 && "ExploreExceptionHandling".equals(frames[0].getClassName()));
thAct.put("fill_in_returns_self", refilled == wrapped);
addCase(cases, "throwable_hierarchy_and_six_methods",
"验证检查型异常/运行时异常/Error 继承关系与 Throwable 的 getMessage、getCause、toString、printStackTrace、getStackTrace、fillInStackTrace 六大方法。",
thExp, thAct);
// Case 2: errorPage -> ShowError.jsp (isErrorPage="true") & JSTL pageContext.errorData via loopback HttpServer
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/main.jsp", exchange -> {
try {
int x = 1;
if (x == 1) {
throw new RuntimeException("Error condition!!!");
}
} catch (Throwable exception) {
// Dispatch to ShowError.jsp (isErrorPage="true")
StringWriter sw = new StringWriter();
exception.printStackTrace(new PrintWriter(sw));
String errorHtml = "status=500|uri=" + exchange.getRequestURI().getPath()
+ "|exception=" + exception.toString()
+ "|frames=" + exception.getStackTrace().length;
byte[] resp = errorHtml.getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().set("Content-Type", "text/plain; charset=UTF-8");
exchange.sendResponseHeaders(500, resp.length);
try (OutputStream os = exchange.getResponseBody()) {
os.write(resp);
}
}
});
server.start();
int errStatus;
String errBody;
try {
int port = server.getAddress().getPort();
HttpURLConnection conn = (HttpURLConnection) new URL("http://127.0.0.1:" + port + "/main.jsp").openConnection();
errStatus = conn.getResponseCode();
errBody = readAll(conn.getErrorStream());
conn.disconnect();
} finally {
server.stop(0);
}
Map<String, Object> epExp = new LinkedHashMap<>();
epExp.put("http_status", 500);
epExp.put("contains_uri", true);
epExp.put("contains_exception_msg", true);
Map<String, Object> epAct = new LinkedHashMap<>();
epAct.put("http_status", errStatus);
epAct.put("contains_uri", errBody.contains("uri=/main.jsp"));
epAct.put("contains_exception_msg", errBody.contains("exception=java.lang.RuntimeException: Error condition!!!"));
addCase(cases, "error_page_dispatch_and_error_data",
"在本地环回 HttpServer 模拟 main.jsp 抛出 RuntimeException 转交 ShowError.jsp,核对 HTTP 500、请求 URI 与异常摘要。",
epExp, epAct);
// Case 3: In-page try...catch handling ArithmeticException (1 / 0)
String tryCatchOutput;
String caughtClass = null;
try {
int i = 1;
int zero = 0;
i = i / zero;
tryCatchOutput = "The answer is " + i;
} catch (Exception e) {
caughtClass = e.getClass().getName();
tryCatchOutput = "An exception occurred: " + e.getMessage();
}
Map<String, Object> tcExp = new LinkedHashMap<>();
tcExp.put("exception_class", "java.lang.ArithmeticException");
tcExp.put("rendered_output", "An exception occurred: / by zero");
Map<String, Object> tcAct = new LinkedHashMap<>();
tcAct.put("exception_class", caughtClass);
tcAct.put("rendered_output", tryCatchOutput);
addCase(cases, "inline_try_catch_divide_by_zero",
"验证页面内联 try...catch 捕获除零 ArithmeticException 并输出 An exception occurred: / by zero。",
tcExp, tcAct);
Map<String, Object> root = new LinkedHashMap<>();
root.put("version", "OpenJDK " + System.getProperty("java.version"));
root.put("cases", cases);
System.out.println(toJson(root));
}
private static String readAll(InputStream in) throws IOException {
if (in == null) return "";
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[512];
int n;
while ((n = in.read(buf)) != -1) out.write(buf, 0, n);
return new String(out.toByteArray(), StandardCharsets.UTF_8);
}
private static void addCase(List<Map<String, Object>> cases, String name, String summary, Object expected, Object actual) {
Map<String, Object> c = new LinkedHashMap<>();
c.put("name", name);
c.put("summary", summary);
c.put("expected", expected);
c.put("actual", actual);
c.put("passed", Objects.equals(expected, actual));
cases.add(c);
}
private static String toJson(Object obj) {
if (obj == null) return "null";
if (obj instanceof Boolean || obj instanceof Number) return obj.toString();
if (obj instanceof String) return escapeString((String) obj);
if (obj instanceof List<?>) {
StringBuilder sb = new StringBuilder("[");
List<?> list = (List<?>) obj;
for (int i = 0; i < list.size(); i++) {
if (i > 0) sb.append(",");
sb.append(toJson(list.get(i)));
}
return sb.append("]").toString();
}
if (obj instanceof Map<?, ?>) {
StringBuilder sb = new StringBuilder("{");
boolean first = true;
for (Map.Entry<?, ?> e : ((Map<?, ?>) obj).entrySet()) {
if (!first) sb.append(",");
first = false;
sb.append(escapeString(String.valueOf(e.getKey()))).append(":").append(toJson(e.getValue()));
}
return sb.append("}").toString();
}
return escapeString(String.valueOf(obj));
}
private static String escapeString(String s) {
StringBuilder sb = new StringBuilder("\"");
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
switch (ch) {
case '"': sb.append("\\\""); break;
case '\\': sb.append("\\\\"); break;
case '\b': sb.append("\\b"); break;
case '\f': sb.append("\\f"); break;
case '\n': sb.append("\\n"); break;
case '\r': sb.append("\\r"); break;
case '\t': sb.append("\\t"); break;
default:
if (ch < 0x20) sb.append(String.format("\\u%04x", (int) ch));
else sb.append(ch);
}
}
return sb.append("\"").toString();
}
}
本例需在 Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。
入口文件:projects/jsp-exception-handling-lab/ExploreExceptionHandling.java
本地运行步骤快速上手
- 点击上方“保存源码”保存为
ExploreExceptionHandling.java,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1397.zip
课程关联工程包(登记关联32章) · 含当前章节或实例 · mbskycom202612a1388.zip