cppsafedivide.cpp

来自「window下的多线程编程参考书。值得一读」· C++ 代码 · 共 60 行

CPP
60
字号
//
// FILE: CppSafeDivide.cpp
//
// Copyright (c) 1997 by Aaron Michael Cohen and Mike Woodring
//
/////////////////////////////////////////////////////////////////////////

#include <windows.h>
#include <stdio.h>
#include <eh.h>             // Defines _set_se_translator.
#include "CppSafeDivide.h"

// The SETranslator function will convert a Win32 structured
// exception into an instance of a CWin32Exception or
// CIntDivideByZero exception object that can be caught
// use the C++ try/catch construct.
//
void SETranslator( unsigned int ExceptionCode, struct _EXCEPTION_POINTERS *pEP )
{
    if( EXCEPTION_INT_DIVIDE_BY_ZERO == ExceptionCode )
    {
        throw CIntDivideByZero(ExceptionCode);
    }
    else
    {
        throw CWin32Exception(ExceptionCode);
    }
}

// CppSafeDivide
//
// Performs a safe division.  If lDivisor is zero,
// CppSafeDivide will return zero.
//
long CppSafeDivide( long lOperand, long lDivisor )
{
    try {
        _set_se_translator(SETranslator);
        return(lOperand / lDivisor);
    }
    catch( CWin32Exception& Info ) {
        printf(
            "Exception 0x%x occurred: %s.\n",
            Info.GetCode(),
            Info.GetText()
        );
    }

    return(0);
}

void main( void )
{
    printf(
        "The result of 2 / 0 is %d.\n",
        CppSafeDivide(2, 0)
    );
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?