In one of my recent posts (Better Excel Scripts : Ansys medini analyze Support) I proposed to use try/catch to intercept an error during an excel import, enrich the error message and rethrow or show an alert dialog. Thats a nice thing, however, it somewhat is a problem if you want t knwo the exact location of the original error.
An example. Assume I have this simple errorneous script:
// $EXPERIMENTAL$ $STRICT_MODE$ $WARNING_AS_ERROR$
var a = [["foo"], undefined];
console.log("{0}", a[0][0]);
console.log("{1}", a[1][2]);
On execution I get: Failed to [...]: Cannot read property [...] (sample.js#4).
So I basically see the file name and line number where I easily can spot the problem and fix the error. If I now wrap this with a try/catch like this:
// $EXPERIMENTAL$ $STRICT_MODE$ $WARNING_AS_ERROR$
try {
var a = [["foo"], undefined];
console.log("{0}", a[0][0]);
console.log("{1}", a[1][2]);
}
catch (e) {
throw e + " with sugar";
}
I get: Failed to [...]: Cannot read property [...] (sample.js#8).
So in line 8 I have the throw statement - no information on the original problematic error. Luckily the exception object has all the information for me:
// $EXPERIMENTAL$ $STRICT_MODE$ $WARNING_AS_ERROR$
try {
var a = [["foo"], undefined];
console.log("{0}", a[0][0]);
console.log("{1}", a[1][2]);
}
catch (e) {
console.log("Exception: {0} {1}#{2}", e.message, e.fileName, e.lineNumber);
throw e + " with sugar";
}
will print to the console: Exception: Cannot read property "2" from undefined sample.js#5
Happy Scripting
Jan