I write a parser for csv files, and sometimes I get a NumberFormatException. Is there an easy way to print the value of an argument that throws an exception?
At the moment, I have many try-catch blocks that look like this:
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(); }
I would like to write something like:
try { builder.ean(Long.parseLong(ean)); } catch (NumberFormatException e) { e.printMethod();
Is there any way to improve my code? And do this type of printing / logging more programmatically?
UPDATE: I tried to implement what Joachim Sauer answered, but I don't know if I got everything right, or if I could improve it. Please give me some feedback. Here is my code:
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); } }
Wrapper Class:
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>"); } } }
Usage example:
try { builder.ean(TrackEx.createBigDecimal(ean)); builder.price(TrackEx.createBigDecimal(price)); } catch (TrackException e) { e.printArg(); e.printMethod(); }
EDIT: Same question, but for .NET: In .net exception, how to get stacktrace with argument values