V
V
Vladimir A2020-10-22 20:37:24
C++ / C#
Vladimir A, 2020-10-22 20:37:24

How to throw exceptions when working with try catch?

What is the best way to deal with exceptions when allocating dynamic memory?

like this?

void foo() {
    int *smth = new int[100];
    try {
        if (5 < 4) {
            std::runtime_error("Беда");
        }
    //тут работа с массивом smth
    } catch (std::runtime_error &e) {
        e.what();
    }
    delete[] smth;
}


the question is whether it is possible to somehow correctly allocate memory inside try and then delete it without leaking memory?

another question about C-th FILE

If you create

FILE *file;

fclose(file)
where to insert fclose(file) when using the same try catch

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
res2001, 2020-10-22
@hauptling

C functions do not throw exceptions. They just don't exist in C. Therefore, there is no point in putting them in try/catch - check return values ​​the old fashioned way. If you like, you can write wrappers for standard functions that throw exceptions on error. It's even better to use std::fstream - you write in C++, so use the plus standard library, not Cishna.

void foo() {
    int *smth;
    try {
        smth = new int[100];
        if (5 < 4) {
            std::runtime_error("Беда");
        }
    } catch (std::runtime_error &e) {
        e.what();
    }
    delete[] smth;
}

new generates std::bad_alloc if an exception occurs - memory has not been allocated and nothing needs to be deleted.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question