P
P
Preis Dmitry2022-04-12 19:28:06
C++ / C#
Preis Dmitry, 2022-04-12 19:28:06

How to display the line where the exception was thrown?

Hello.
I need to define several native data types that have some operations defined that can throw errors. As an example:

int main() {
    int length = 10;
    auto arr = MyAwesomeArray<int>(length);
    arr[15] = 2; // IndexOutOfRangeException();

    return 0;
}


I have described the error class like this

class IndexOutOfRangeException : public std::exception {
private:
    std::string m_error;

public:
    explicit IndexOutOfRangeException(std::string error) : m_error(std::move(error)) {}

    const char *what() const noexcept override { return m_error.c_str(); }
};

Which produces such a message

terminate called after throwing an instance of 'IndexOutOfRangeException'
  what():  some error message

And everything works well (an error is raised, the program terminates).

But in this case, it is extremely inconvenient to use these errors, because in this message neither the file nor the line on which the exception was thrown is shown. How to make the same (or similar) output as for standard errors?
test.cpp: In function ‘int main()’:
test.cpp:29:5: error: ‘foobar’ was not declared in this scope
   29 |     foobar();
      |     ^~~~~~

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vitaly, 2022-04-13
@Preisy

There is a wonderful functionality: https://en.cppreference.com/w/cpp/utility/source_l...
Available since C++20. I will form local experts at the same time :)
Well, or macros.

A
Armenian Radio, 2022-04-12
@gbg

It is important to understand that at the time of program execution (runtime) information about the source code of the program is no longer available.
Options
1) Build the program with debugging information and parse the stack when an exception is thrown, similar to how a debugger does it.
2) Do catch on each line and use macros __FILE__ and __LINE__

A
Adamos, 2022-04-12
@Adamos

You are going against the C++ ideology, which assumes that the compiled code will only do what the algorithm really needs. In order to do a bunch of other things in case when it will be necessary to show the unfortunate programmer where he screwed up - there are many, many other languages.
Right, if there was an easy and natural way to make such debugging information - do you really think that the STL developers would not use such a possibility?
On the other hand, an exception is thrown by the container method and a string is passed to it. You can also add some data of the container itself to this line, which can be useful in investigating the error - its real length, type, erroneous index....

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question