編寫一個函式求平方根,如果輸入的是負數,丟擲自定義型別的異常。如果輸出的是正數和零,則正常輸出其平方根...

weixin_33866037發表於2018-06-21

squareErr

#pragma once
#include <stdexcept>
using namespace std;

class squareErr : public exception
{
public:
    squareErr();
    ~squareErr();
    const char *what() const;
};

squareErr.cpp

#include "stdafx.h"
#include "squareErr.h"
#include <iostream>
using namespace std;

squareErr::squareErr()
{
}

const char * squareErr::what() const{
    return "平方根引數不能為負";
}

squareErr::~squareErr()
{
}

main.cpp

// 異常處理-23期-92-子羽.cpp : 定義控制檯應用程式的入口點。
//

#include "stdafx.h"
#include <iostream>
#include <stdexcept>
#include "squareErr.h"
#include <cmath>
using namespace std;

float square(float num) {
    if (num < 0)
    {
        throw squareErr();
    }
    return sqrt(num);
}

int _tmain(int argc, _TCHAR* argv[])
{
    try
    {
        square(-10);
    }
    catch (squareErr ex)
    {
        cout << ex.what() << endl;
    }

    return 0;
}


相關文章