实现说明
逻辑集中在类 StackTraceText和函数 main里。
IllegalStateException 在 try 块内抛出——谁来接住由匹配的 except 子句决定,与任何输入检查无关。
使用要点
- 直接运行文件,输出会带上标签,比如
has frames:、has message:——输出的每一行都能指回产生它的那次调用。
常见问题
这个示例会校验输入吗?
不会——IllegalStateException 在 try 块内抛出:执行到这一行就必然抛出,由外围的 except 子句决定谁来接住。示例里没有输入校验。
运行「用 PrintWriter 把堆栈转成字符串」会打印什么?
文件本身就是完整程序,直接运行——输出行带有 has frames:、has message: 这类标签。
核心语句
throw new IllegalStateException("boom in service");
代码示例
import java.io.PrintWriter;
import java.io.StringWriter;
public class StackTraceText {
public static void main(String[] args) {
try {
throw new IllegalStateException("boom in service");
} catch (IllegalStateException failure) {
StringWriter sink = new StringWriter();
failure.printStackTrace(new PrintWriter(sink));
String trace = sink.toString();
System.out.println(trace.split("\n")[0]);
System.out.println("has frames: " + trace.contains("StackTraceText.main"));
System.out.println("has message: " + trace.contains("boom in service"));
}
}
}