0

In the following codes:

const int ME_ABORT_EXCEPTION = 1;

class CMyException
{
public:
    CMyException(int nErrorCode)
    : m_nErrorCode(nErrorCode)
    {
    }

    ~CMyException()
    {
    }

    int m_nErrorCode;   
};

void CTestExceptionDlg::OnBnClickedButton1()
{
    // TODO: Add your control notification handler code here
    try
    {
        throw CMyException(ME_ABORT_EXCEPTION);
    }
#pragma warning(disable:4101)
    catch(CMyException& e)
    {
        ASSERT(e.m_nErrorCode == ME_ABORT_EXCEPTION);
    }
#pragma warning(default:4101)
}

I try to disable the compiler warning C4101 with #pragma, but it does not work. When compiling Release version, there will still be compiler warning. Why?

The warning message is:

warning C4101: 'e' : unreferenced local variable
9
  • Please explain what the warning is. Very few people memorize Microsoft's numerical codes.
    – molbdnilo
    Commented Dec 19, 2019 at 8:26
  • @molbdnilo, OK, I have added the warning message.
    – alancc
    Commented Dec 19, 2019 at 8:35
  • 1
    You could just remove the variable name if you don't need it. catch(CMyException&) {...} is perfectly valid.
    – Lukas-T
    Commented Dec 19, 2019 at 8:37
  • 1
    From memory, Microsoft docs say that, for some range of warning numbers, if a #pragma warning is in a function block, it doesn't have effect until after the function block. I don't know offhand if C4101 is in that range, but it is a possibility. In any event, rather than using a pragma (inherently a compiler-specific hook, that will often not work with other compilers) simply change the catch to catch(CMyException &) (remove the name e). Also, preferably, make it const.
    – Peter
    Commented Dec 19, 2019 at 8:46
  • 2
    catch([[maybe_unused]]CMyException& e) since C++17.
    – Jarod42
    Commented Dec 19, 2019 at 9:11

1 Answer 1

2

As noted in the comments, the C4101 warning works at function scope, so you have to disable it before/outside the function(s) you want to apply it to:

#pragma warning(disable:4101)
void CTestExceptionDlg::OnBnClickedButton1()
{
    // TODO: Add your control notification handler code here
    try
    {
        throw CMyException(ME_ABORT_EXCEPTION);
    }
    catch (CMyException & e)
    {
        ASSERT(e.m_nErrorCode == ME_ABORT_EXCEPTION);
    }
}
#pragma warning(default:4101)

I've tested this in VS2010 and it works. In VS2017 and VS2019, the warning is also disabled as expected in your original code arrangement.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.