SOFTIST 编程方法筆記 →目录

CException类的派生与使用(VC++)

VC++程序的例外产生方法的笔记。派生CException类,在需要投掷例外时使用。VC++基本上是利用下面的throw+try+catch机构来处理例外。

try
{
    ... ...
    某种有可能发生例外的处理();
    ... ...
}
catch(CException *e)
{
    e->显示例外内容等的処理();
    e->Delete();
}

某种有可能发生例外的处理()
{
    ... ...
    throw new CException();
    ... ...
}

 

例题:「不可为三」。产生随机整数,如果这个数是3的倍数倍,就投掷例外。

//装载派生类
class CMyException : public CException
{
public:
    int m_nError;
    CMyException(int nError = 3) 
    {
#ifdef _DEBUG
        m_bReadyForDelete = TRUE;
#endif
        m_nError = nError;
    }
    void Delete() {delete this;}
    int ReportError()
    {
        CString strText;
        strText.Format(_T("数字 %d 与3有关系,不行!"), m_nError);
        AfxMessageBox(strText, MB_OK);
        return 0;
    }
};

//生成随机数处理
int NumberBut3()
{
    int iNum = rand();
    if (iNum % 3 == 0 && iNum != 0)
    {
        //3的倍数时
        throw new CMyException(iNum);
    }
    return iNum;
}

void Test()
{
    for (int i = 0; i < 5; i ++)
    {
        try
        {
            int idat = NumberBut3();
            CString strMess;
            strMess.Format(_T("第 %d 次的字是 %d 。安全!"), i, idat);
            AfxMessageBox(strMess);
        }
        catch (CMyException* e)
        {
            e->ReportError();
            e->Delete();
            break;
        }
    }
}