Enums and Exceptions

Plain Enum - The C way

#include <iostream>
using namespace std;

enum Season {
    WINTER,    // = 0 by default
    SPRING,    // = WINTER + 1
    SUMMER,    // = WINTER + 2
    AUTUMN        // = WINTER + 3
};

int WINTER = 60;  // won't compile - redefinition

int main() {
    cout << WINTER;
    int curr_season = WINTER;
    curr_season += 50;
    cout << curr_season << endl;
    cout << (curr_season==0) << endl;
}

1st - This won't compile because on line 12 we are redefing winter. No variable can have a name which is already in some enumeration.

2nd - usually curr_season += 50; usually wouldn't make sense and also this could be very dangerous.

To prevent these mishaps c++ has included enum class. The original c-styled enum may be used if desired.

Enum Class - The C++ way

output

The following is much more understandable.

We could also do the following to print out which month it is

Safety prevention in Enum Class

The enum isn't treated like and integer like the c-styled version therefore the following won't compile

This would work in the C version. In order to print the intger value wiht enum class we must cast it to an int

since curr_season isn't an integer the none of the following wouldnt work either

rather we can do the following

Other good examples of enums

Exceptions

To prevent early termination of a program we mush throw and catch an exception by using the keywords throw, try and catch

output

Throwing a String

Instead of throwing an int we can throw a string

output

The function sqrt will return a nan (not a number) if the input is below zero

Our function safesqrt returns a double

To prevent terminate called after throwing... if we were to only run the following

We must catch the exception of type string the type that was thrown on lines 4-6

Throwing a Standard Exception Object

we can use a standard expction such as std::out_of_range

notice line 3

similarly we must catch a std::exception object (or reference to one)

notice line 4 it is a std::exception& type instead of the string type before catch (string message)

the what function will display the string given to the constructor of the object

Multiple handlers and Any Exception

catch expressions can be chained with the relavent handler catching the exception

Additionally we can catch any exception by using three dots ...

Throwing an object

first create an object

next throw the object in the desired place

and we can catch the error using ellipsis (three dots) ...

Last updated