try catch __finally 在 C++ Builder 中使用

try catch __finally use in C++ Builder

我认为这段代码是否正确:

try
    {
    Screen->Cursor = crHourGlass;
    try
        {
        throw Exception("error!");
        }
    catch(Exception& e)
        {
        Application->MessageBox(UnicodeString(e.Message).c_str(), L"Error", MB_OK);
        }
    }
__finally
    {
    Screen->Cursor = crDefault;
    }

实际上与这个相同,__finally 在这里没有任何作用,因为在这两种情况下 Screen->Cursor = crDefault 无论如何都会被执行?

Screen->Cursor = crHourGlass;
try
    {
    throw Exception("error!");
    }
catch(Exception& e)
    {
    Application->MessageBox(UnicodeString(e.Message).c_str(), L"Error", MB_OK);
    }
Screen->Cursor = crDefault;

不,因为您只捕获 Exception 类型的异常。如果发生其他异常,则 Screen->Cursor = crDefault 将不会在第二版代码中执行。

回答你的问题 - 不,它们 相同 ,因为如果有什么东西,crDefault 分配在第二个版本中被跳过的可能性很小意外发生。第一个版本中的 __finally 通常会处理该问题。

也就是说,替代方法是使用 RAII 容器而不是 __finally,例如:

class TUpdateScreenCursor
{
private:
    TCursor m_Original;

public:
    TUpdateScreenCursor(TCursor NewCursor)
    {
        m_Original = Screen->Cursor;
        Screen->Cursor = NewCursor;
    }

    ~TUpdateScreenCursor()
    {
        Screen->Cursor = m_Original;
    }
};

{
TUpdateScreenCursor sc(crHourGlass);
try
    {
    throw Exception("error!");
    }
catch (const Exception& e)
    {
    Application->MessageBox(e.Message.c_str(), _D("Error"), MB_OK);
    }
}