這是非常艱苦的工作,但這裏是解析一些實時異常生成的例外的演示。
- 該方法被稱爲generate_ $來試圖覆蓋奇怪的命名方法。我確定我沒有覆蓋所有案例。
- 將它們重構爲java.lang.StackTraceElement的列表,因爲它看起來是作業的正確類型。
代碼:
private static List<String> generate_$() {
List<String> returnValue = new LinkedList<String>();
Exception[] exceptions = { new ClassCastException(),
new NullPointerException(), new IOException("foo") };
for (Exception exception : exceptions) {
try {
throw exception;
} catch (Exception e) {
StringWriter writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
returnValue.add(writer.getBuffer().toString());
}
}
return returnValue;
}
public static void main(String[] args) {
List<String> examples = generate_$();
for (String trace : examples) {
Pattern headLinePattern = Pattern.compile("([\\w\\.]+)(:.*)?");
Matcher headLineMatcher = headLinePattern.matcher(trace);
if (headLineMatcher.find()) {
System.out.println("Headline: " + headLineMatcher.group(1));
if (headLineMatcher.group(2) != null) {
System.out.println("Optional message "
+ headLineMatcher.group(2));
}
}
// "at package.class.method(source.java:123)"
Pattern tracePattern = Pattern
.compile("\\s*at\\s+([\\w\\.$_]+)\\.([\\w$_]+)(\\(.*java)?:(\\d+)\\)(\\n|\\r\\n)");
Matcher traceMatcher = tracePattern.matcher(trace);
List<StackTraceElement> stackTrace = new ArrayList<StackTraceElement>();
while (traceMatcher.find()) {
String className = traceMatcher.group(1);
String methodName = traceMatcher.group(2);
String sourceFile = traceMatcher.group(3);
int lineNum = Integer.parseInt(traceMatcher.group(4));
stackTrace.add(new StackTraceElement(className, methodName,
sourceFile, lineNum));
}
System.out.println("Stack: " + stackTrace);
}
}
輸出:
Headline: java.lang.ClassCastException
Stack: [com.adamish.ExceptionParse.generate_$((ExceptionParse.java:16), com.adamish.ExceptionParse.main((ExceptionParse.java:31)]
Headline: java.lang.NullPointerException
Stack: [com.adamish.ExceptionParse.generate_$((ExceptionParse.java:17), com.adamish.ExceptionParse.main((ExceptionParse.java:31)]
Headline: java.io.IOException
Optional message : foo
Stack: [com.adamish.ExceptionParse.generate_$((ExceptionParse.java:17), com.adamish.ExceptionParse.main((ExceptionParse.java:31)]
如果你精心設計的系統,你會在適當的地方已經被捕獲的異常,並會顯示相應的人類可讀的消息。如果你想寫一個分析別人的應用程序錯誤的應用程序。我認爲該應用可能最終變得模糊。只是我的想法。 – Nishant 2012-04-04 15:07:56