How to catch line number of exception without catching it ?

Jonathan M Davis newsgroup.d at jmdavisprog.com
Wed Dec 13 19:39:52 UTC 2017


On Wednesday, December 13, 2017 18:24:09 Thomas via Digitalmars-d-learn 
wrote:
> Hi forks!
>
> I wanted to ask if there is a way to catch the line position on
> an exception without setting a try + catch block ?
> What I want is something like this:
>
>
> module main;
>
> import std.stdio;
> import std.conv;
>
> void foo()
> {
>   scope(failure)
>   {
>       writeln("Got a failure in ", __FILE__, " ", __FUNCTION__, "!" );
>       // what I miss is the line position with __LINE__
>   }
>
>   int x = to!int("1x");  // <-- here is the exception throwing
>
> }
>
> int main()
> {
>   foo();
>   return 0;
> }
>
>
> My goal is to trace the failure from the branch back to the root
> like this:
>
> (error) in "module2" at "foo2()" on line "..."
> (error) in "module1" at "foo1()" on line "..."
> (error) in "main" at "main()" on line "..."
>
> I don't want to set on every function a try + catch functionality
> because I think it is not a good coding style. Also I dont want
> to send on every possible position where an exception/error could
> happen (even when catched) the line position into an error log
> function. So I got the idea of writing out modulename and
> function with scope(failure) on the beginning of each function,
> which works great recursive, but only the line position is
> missing.
> So my question is: Is there a way to catch that line where the
> exception has happened without a catch ?
>
> Or is there a better solution for tracing the error position from
> root till the branch ?

If you want access to an exception in flight, you must catch it and rethrow
it. There is no other way.

But normally, if you want to see the stack when an exception was thrown,
you'd either use a debugger, or you'd look at the stack trace that gets
printed when the exception exits main (though unfortunately, as I understand
it, there's currently a regression, and the line numbers don't show up in
stack traces on Linux anymore, even when you compile with -g).

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list