Home > Development > C++ Exceptions

C++ Exceptions


So I am going to post a pretty well know example in programming on the classic divide by zero issue.

#include <iostream>
#include <string>

using namespace std;

class DivideZeroException{
private:
    string message;
public:
    DivideZeroException(const string& message);
    string getMessage() const;

};

DivideZeroException::DivideZeroException(const string &message){
    this->message = message;
}

string DivideZeroException::getMessage() const{
    return this->getMessage();
}

class Math{
public:
    static double Divide(double number, double divisor);
};

double Math::Divide(double number, double divisor){
    if(divisor == 0)
        throw DivideZeroException("You can not divide by zero");
    return number / divisor;
}

int main(){

    int number = 10;
    int divisor = 0;

    try{

        double result = Math::Divide(number,divisor);
        cout << "Result: " << result << endl;

    }catch(DivideZeroException& exception){
        cout << exception.getMessage() << endl;
    }

    return 0;
}

You can see that we throw an exception when the divisor == 0 and catch it in the calling code. The golden rule in C++ exception handling vs C# is that you throw by value and catch by reference. Why? When the stack is unwinding if you use a reference to a stack variable it will not be able to be referenced and if you throw by pointer then you have to deallocate memory in the catch blocks.

Blair..

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: