Answer the question
In order to leave comments, you need to log in
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;
}
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(); }
};
terminate called after throwing an instance of 'IndexOutOfRangeException'
what(): some error message
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
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.
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__
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 questionAsk a Question
731 491 924 answers to any question