0

In c++, let say there is a system exception in some Line, in catch block is it possible to get the line number from where the exception has occurred.

void main()
{
   try
   {
     //Line 1
     //Line 2  // system exception in Line 2
     //Line 3
   }
   catch(exception e)
   {
    // how to get that exception has occurred in Line2
   }
}

Thanks, Samson

secuman
  • 539
  • 4
  • 12
  • In C++, you don't have access to that information. – molbdnilo Sep 01 '21 at 12:41
  • No, I don't think so. [How to know the exact line of code where an exception has been caused?](https://stackoverflow.com/a/350378) – 001 Sep 01 '21 at 12:41
  • Just curious: was this something you wanted to know in general or are you trying to debug a real issue somewhere? – Pepijn Kramer Sep 01 '21 at 15:13
  • *"system exception"* - In context of Windows programming this usually means an SEH exception. In that case you don't even get to handle it in your C++ exception handler (unless you opt in to non-standard behavior). Luckily, though, you don't have to do anything special (other than registering your application with WER) to get a full dump of the process at the time the exception was raised (assuming that you aren't actually handling it, which you shouldn't). – IInspectable Sep 01 '21 at 16:26
  • @PKramer actually i am trying to add this feature in my project – Samson Petersingh Sep 02 '21 at 08:05

1 Answers1

0

It is not available out of the box. But if you are willing to add an extra exception class to your hierarchy it can be done like this (only tested on MSVC):

#include <iostream>
#include <exception>
#include <string>

class file_line_exception : public std::exception
{
public:
    template<size_t N>
    file_line_exception(const char(&file)[N], size_t line, const std::string& what) :
        std::exception{ what.c_str() },
        m_file{ file },
        m_line{ std::to_string(line) }
    {
    }

    const std::string& file() const noexcept
    {
        return m_file;
    }

    const std::string& line() const noexcept
    {
        return m_line;
    }

private:
    std::string m_file;
    std::string m_line;
};

int main()
{
    try
    {
        throw file_line_exception(__FILE__, __LINE__, "some kind of descrition");
    }
    catch (const file_line_exception& e)
    {
        std::cout << "exception from : " << e.file() << "(" << e.line() << ") : " << e.what() << std::endl;
    }
}
Pepijn Kramer
  • 9,356
  • 2
  • 8
  • 19
  • "throw file_line_exception(__FILE__, __LINE__, "some kind of descrition"); " But we know that this line is going to throw exception. What if i don't use throw statement but that line gives exception. – Samson Petersingh Sep 01 '21 at 13:21
  • There's [source_location](https://en.cppreference.com/w/cpp/utility/source_location) starting with C++20. This would be a prime candidate for it. – IInspectable Sep 01 '21 at 14:00