【发布时间】:2011-01-27 17:29:57
【问题描述】:
我正在为 csv 文件编写解析器,但有时会遇到 NumberFormatException。有没有一种简单的方法可以打印导致异常的参数值?
目前我是否有 很多 个如下所示的 try-catch 块:
String ean;
String price;
try {
builder.ean(Long.parseLong(ean));
} catch (NumberFormatException e) {
System.out.println("EAN: " + ean);
e.printStackTrace();
}
try {
builder.price(new BigDecimal(price));
} catch (NumberFormatException e) {
System.out.println("Price: " + price);
e.printStackTrace();
}
我希望能够写出类似的东西:
try {
builder.ean(Long.parseLong(ean));
} catch (NumberFormatException e) {
e.printMethod(); // Long.parseLong()
e.printArgument(); // should print the string ean "99013241.23"
e.printStackTrace();
}
有什么方法可以至少改进我的代码吗?并以编程方式进行这种打印/记录?
更新:我尝试实现 Joachim Sauer 回答的内容,但我不知道我是否做对了一切,或者我是否可以改进它。请给我一些反馈。这是我的代码:
public class TrackException extends NumberFormatException {
private final String arg;
private final String method;
public TrackException (String arg, String method) {
this.arg = arg;
this.method = method;
}
public void printArg() {
System.err.println("Argument: " + arg);
}
public void printMethod() {
System.err.println("Method: " + method);
}
}
包装类:
import java.math.BigDecimal;
public class TrackEx {
public static Long parseLong(String arg) throws TrackException {
try {
return Long.parseLong(arg);
} catch (NumberFormatException e) {
throw new TrackException(arg, "Long.parseLong");
}
}
public static BigDecimal createBigDecimal(String arg) throws TrackException {
try {
return new BigDecimal(arg);
} catch (NumberFormatException e) {
throw new TrackException(arg, "BigDecimal.<init>");
}
}
}
使用示例:
try {
builder.ean(TrackEx.createBigDecimal(ean));
builder.price(TrackEx.createBigDecimal(price));
} catch (TrackException e) {
e.printArg();
e.printMethod();
}
编辑:同样的问题,但对于 .NET:In a .net Exception how to get a stacktrace with argument values
【问题讨论】:
-
关于您的解决方案:基本上就是这样,但我会改变两件事:1.) 提供原因(通过在构造函数中调用
initCause(),因为NumberFormatException没有构造函数)和 2.)用适当的 getter 替换printArg()和printMethod()方法,因为打印到System.err可能不是开发人员想要对这些值执行的操作。 -
@Joachim Sauer:非常感谢,这是个好建议!
标签: java logging exception-handling try-catch