Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know the exact line of code where an exception has been caused?

Tags:

c++

exception

If I generate an exception on my own, I can include any info into the exception: a number of code line and name of source file. Something like this:

throw std::exception("myFile.cpp:255");

But what's with unhandled exceptions or with exceptions that were not generated by me?

like image 384
Mar Avatar asked Dec 08 '08 07:12

Mar


People also ask

How can I get the line number which threw exception?

Simple way, use the Exception. ToString() function, it will return the line after the exception description. You can also check the program debug database as it contains debug info/logs about the whole application.

How do you find the error line in C++?

There's no way in Standard C++ that you could find line C without passing it in as an argument ( f(-6, __LINE__) ), and no way at all that you could find Line A. +1, but I'd say "a stack trace or a debugger", since a stack trace can be obtained even without an external debugger (see e.g. the backtrace function).

What happen in the program when an exception occurs?

Definition: An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. When an error occurs within a method, the method creates an object and hands it off to the runtime system.


10 Answers

A better solution is to use a custom class and a macro. :-)

#include <iostream> #include <sstream> #include <stdexcept> #include <string>  class my_exception : public std::runtime_error {     std::string msg; public:     my_exception(const std::string &arg, const char *file, int line) :     std::runtime_error(arg) {         std::ostringstream o;         o << file << ":" << line << ": " << arg;         msg = o.str();     }     ~my_exception() throw() {}     const char *what() const throw() {         return msg.c_str();     } }; #define throw_line(arg) throw my_exception(arg, __FILE__, __LINE__);  void f() {     throw_line("Oh no!"); }  int main() {     try {         f();     }     catch (const std::runtime_error &ex) {         std::cout << ex.what() << std::endl;     } } 
like image 123
Frank Krueger Avatar answered Sep 28 '22 17:09

Frank Krueger


It seems everyone is trying to improve your code to throw exceptions in your code, and no one is attempting the actual question you asked.

Which is because it can't be done. If the code that's throwing the exception is only presented in binary form (e.g. in a LIB or DLL file), then the line number is gone, and there's no way to connect the object to to a line in the source code.

like image 39
James Curran Avatar answered Sep 28 '22 16:09

James Curran


There are several possibilities to find out where the exception was thrown:

Using compiler macros

Using __FILE__ and __LINE__ macros at throw location (as already shown by other commenters), either by using them in std exceptions as text, or as separate arguments to a custom exception:

Either use

throw std::runtime_error(msg " at " `__FILE__` ":" `__LINE__`);

or throw

class my_custom_exception {
  my_custom_exception(const char* msg, const char* file, unsigned int line)
...

Note that even when compiling for Unicode (in Visual Studio), FILE expands to a single-byte string. This works in debug and release. Unfortunately, source file names with code throwing exceptions are placed in the output executable.

Stack Walking

Find out exception location by walking the call stack.

  • On Linux with gcc the functions backtrace() and backtrace_symbols() can get infos about the current call stack. See the gcc documentation how to use them. The code must be compiled with -g, so that debug symbols are placed in the executable.

  • On Windows, you can walk the stack using the dbghelp library and its function StackWalk64. See Jochen Kalmbach's article on CodeProject for details. This works in debug and release, and you need to ship .pdb files for all modules you want infos about.

You can even combine the two solutions by collecting call stack info when a custom exception is thrown. The call stack can be stored in the exception, just like in .NET or Java. Note that collecting call stack on Win32 is very slow (my latest test showed about 6 collected call stacks per second). If your code throws many exceptions, this approach slows down your program considerably.

like image 41
vividos Avatar answered Sep 28 '22 17:09

vividos


If you have a debug build and run it in the Visual Studio debugger, then you can break into the debugger when any kind of exception is thrown, before it propagates to the world.

Enable this with the Debug > Exceptions menu alternative and then check-marking the kinds of exceptions that you are interested in.

You can also add the ability to create a dump file, if the application source code is your own. With the dump file and PDB files (symbols) for the specific build, you'll get stacktraces with WinDbg, for example.

like image 41
Johann Gerell Avatar answered Sep 28 '22 17:09

Johann Gerell


No one mentioned boost so far. If you're using boost c++ libraries they do come with some nice exception defaults for this:

#include <boost/exception/diagnostic_information.hpp>
#include <exception>
#include <iostream>

struct MyException : std::exception {};

int main()
{
  try
  {
    BOOST_THROW_EXCEPTION(MyException());
  }
  catch (MyException &ex)
  {
    std::cerr << "Unexpected exception, diagnostic information follows:\n"
              << boost::current_exception_diagnostic_information();
  }
  return 0;
}

And then you might get something like:

Unexpected exception, diagnostic information follows:
main.cpp(10): Throw in function int main()
Dynamic exception type: boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<MyException> >
std::exception::what: std::exception

Docs: https://www.boost.org/doc/libs/1_63_0/libs/exception/doc/diagnostic_information.html

like image 29
Dominic Avatar answered Sep 28 '22 16:09

Dominic


Inspired by Frank Krueger's answer and the documentation for std::nested_exception, I realized that you can combine Frank's answer, which I've been using for a while, with std::nested_exception to create a full error stack trace with file & line info. For example with my implementation, running

#include "Thrower.h"
#include <iostream>
// runs the sample function above and prints the caught exception
int main ( )
{
    try {
        // [Doing important stuff...]
        try {
            std::string s = "Hello, world!";
            try {
                int i = std::stoi ( s );
            }
            catch ( ... ) {
                thrower ( "Failed to convert string \"" + s + "\" to an integer!" );
            }
        }
        catch ( Error& e ) {
            thrower ( "Failed to [Do important stuff]!" );
        }
    }
    catch ( Error& e ) {
        std::cout << Error::getErrorStack ( e );
    }
    std::cin.get ( );
}

outputs

ERROR: Failed to [Do important stuff]!
@ Location:c:\path\main.cpp; line 33
 ERROR: Failed to convert string "Hello, world!" to an integer!
 @ Location:c:\path\main.cpp; line 28
  ERROR: invalid stoi argument

Here's my implementation:

#include <sstream>
#include <stdexcept>
#include <regex>

class Error : public std::runtime_error
{
    public:
    Error ( const std::string &arg, const char *file, int line ) : std::runtime_error( arg )
    {
        loc = std::string ( file ) + "; line " + std::to_string ( line );
        std::ostringstream out;
        out << arg << "\n@ Location:" << loc;
        msg = out.str( );
        bareMsg = arg;      
    }
    ~Error( ) throw() {}

    const char * what( ) const throw()
    {
        return msg.c_str( );
    }
    std::string whatBare( ) const throw()
    {
        return bareMsg;
    }
    std::string whatLoc ( ) const throw( )
    {
        return loc;
    }
    static std::string getErrorStack ( const std::exception& e, unsigned int level = 0)
    {
        std::string msg = "ERROR: " + std::string(e.what ( ));
        std::regex r ( "\n" );
        msg = std::regex_replace ( msg, r, "\n"+std::string ( level, ' ' ) );
        std::string stackMsg = std::string ( level, ' ' ) + msg + "\n";
        try
        {
            std::rethrow_if_nested ( e );
        }
        catch ( const std::exception& e )
        {
            stackMsg += getErrorStack ( e, level + 1 );
        }
        return stackMsg;
    }
    private:
        std::string msg;
        std::string bareMsg;
        std::string loc;
};

// (Important modification here)
// the following gives any throw call file and line information.
// throw_with_nested makes it possible to chain thrower calls and get a full error stack traceback
#define thrower(arg) std::throw_with_nested( Error(arg, __FILE__, __LINE__) )

```

like image 29
aquirdturtle Avatar answered Sep 28 '22 18:09

aquirdturtle


I think that a stack trace should get you to the point.

like image 29
Marcin Gil Avatar answered Sep 28 '22 17:09

Marcin Gil


I found 2 solutions, but neither is fully satisfactory:

  1. If you call std::set_terminate, you can from there print the callstack right from the third party exception throw. Unfortunately, there's no way to recover from a terminate handler, and hence your application will die.

  2. If you call std::set_unexpected, then you need to declare as many as possible from your functions with throw(MyControlledException), so that when they throw due to third party called functions, your unexpected_handler will be able to give you a fine-grained idea of where your application threw.

like image 38
Daniel Pinyol Avatar answered Sep 28 '22 16:09

Daniel Pinyol


Compile your software in debug mode and run it with valgrind. It is mainly for finding memory leaks but it can also show you the exact line of where exceptions occur valgrind --leak-check=full /path/to/your/software.

like image 20
Spixmaster Avatar answered Sep 28 '22 18:09

Spixmaster


Others have already proposed using a macro and possibly a custom class. But in case you have an exception hierarchy, you need to also specify the exception type while throwing:

#define THROW(ExceptionType, message)                                    \
    throw ExceptionType(std::string(message) + " in " + __FILE__ + ':'   \
                        + std::to_string(__LINE__) + ':' + __func__)

THROW(Error, "An error occurred");

The assumption here is that all exceptions accept a single string argument, which is not limiting, as one can convert other arguments to strings (e.g. with std::to_string()) and concatenate them to a single string.

like image 22
mrts Avatar answered Sep 28 '22 16:09

mrts