C ++ class constructor throwing an exception

Let's consider the existence of a class with a constructorthrowing an exception as shown below:

class Class
{
    public:
        Class(type argument)
        {
            if (argument == NULL)
            {
                throw std::exception("Value cannot be null.\nParameter name: argument");
            }

            // Instructions
        }
    private:
        // Properties
}

Since class constructor may throw an exception , we cannot declare an object directly.

Class obj(argument); // Harmful

This means that constructor constructor must be called using try / catch

try
{
    Class obj(argument);
}
catch (std::exception& ex)
{
    std::cout << ex.what() << std::endl;
}

The problem is that we can only use the object inside the try block . The only way to use it outside the try block is to declare a Class * pointer , , .

Class* pObj;

try
{
    pObj = new Class(argument);
}
catch (std::exception& ex)
{
    std::cout << ex.what() << std::endl;
}

, ?

+4
2

, .

, . try, , . , ( , , ).

, , , , .

try {
    Class obj(argument);
    // use obj here, inside the try block
}
catch(...) { ... }

// not here, outside the try block

: , , . , exaqmple. , , :

void Foobar(type argument)
{
    Class obj(argument);
    obj.method1(1,2,3);
    obj.method2(3,4);
    int x = Wizbang(obj);
    gobble(x);    
}

, Class. , , , try, :

void Foobar(type argument)
{
    try
    {
        Class obj(argument);
        obj.method1(1,2,3);
        obj.method2(3,4);
        int x = Wizbang(obj);
        gobble(x);
    }
    catch(std::exception& e)
    {
        std::cout << e.what() << std::endl;
    }
}

, , . : " ", , "" " try, ". , .

+3

, , (). , - , , obj Class, - try {} catch {} , . : obj , - , , obj , obj? , obj????

0

All Articles