Похожие чаты

Is the dtor called but just actually not displayed on

the console ? (when throwing an exception)

11 ответов

8 просмотров

1) never use: using namespace std; https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice 2) desctructor is called, but to test this it's better to use try-catch: https://godbolt.org/z/M6zq6Wzov

It depends on the ABI. The C++ standard guarantees that destructors will be run when the stack is unwound. But in this case, the stack is not unwound. Exception handling in x86_64 happens in two stages. In the first stage, a personality routine is run to check where the matching catch handler is found. In the second stage the stack is unwound till the function where the catch handler is located and the destructor is run for all local objects in the stack frames that were destroyed. In your case, no catch handler is found and hence it is not guaranteed that destructors will be run. It is also entirely possible for an ABI to define that destructors will be run in such cases. The C++ standard does not guarantee this but. It depends entirely on the ABI.

Sahand-🏔️ Автор вопроса
Madhu
It depends on the ABI. The C++ standard guarantees...

So do I need to clear() my objects before throwing the exception? However I think this is not really an effective way. For example, what about allocated data for other objects ? They won't be freed up

Sahand 🏔️
So do I need to clear() my objects before throwing...

What is the use of throwing an exception if you won't catch it anywhere? The process will be terminated anyway

Sahand-🏔️ Автор вопроса
Madhu
What is the use of throwing an exception if you wo...

So just using a try/catch will be fine ?

Sahand 🏔️
So just using a try/catch will be fine ?

Yes having a catch block somewhere that can handle the exception will ensure that destructors in the wound up stacks are run. I however think that you don't understand exceptions completely yet. I would suggest reading Herb Sutter's guide to exception handling to understand it before using it in your code. It cant be explained easily here.

If you throw an exception try to catch it (otherwise there'll most probably be a crash). If you catch your exception, the dtor is called. You could also try and test it.

Sahand-🏔️ Автор вопроса
Azadi
If you throw an exception try to catch it (otherwi...

Yeah, I would like the program to crash. That's my preference. For example when the user attempts to access a block of memory that doesn't exist (which is seg fault)

Sahand 🏔️
Yeah, I would like the program to crash. That's my...

If a SEGFAULT occurs, why would you need to even bother about exceptions? The OS would signal your process in this case. Like I said earlier, please read more about exceptions and also the use cases where they would be relevant.

Sahand-🏔️ Автор вопроса
Madhu
If a SEGFAULT occurs, why would you need to even b...

Oh ok. I thought I should care about any possible misuse of my program

Sahand 🏔️
Yeah, I would like the program to crash. That's my...

I don't know of any case in which crashing is considered fine. You could handle the exception, let the user know of their mistake and then terminate the program. That's much better.

Похожие вопросы

Обсуждают сегодня

At which price point will BCH, an ASIC mined coin, be succeptible to reorg attacks because of low hashrate? $10? $1? $0.1? $0.01?
Kishniev
18
А кто-то пробовал, уезжая из Эстонии получить э-рез и продолжить вести предпринимательскую деятельность внутри Эстонии, используя свой OÜ?
Lalalashechki Lalala
62
зачем же переименовывать ? чтобы кол-во участников возросло или вдруг IBM от этого снова на свифте начнет кодить ? Я не понимаю что страшного в том что свифт гавно, если это т...
Oleh Nerzh
10
Is Kadena onto something special? No one really knows. Good luck!
Bright Uncle Stephen EqualBet
40
Гайз, кто-нибудь пробовал запустить probe-rs под камень, которого нет в probe-rs? Мб есть какой-нибудь пример у кого... Через target-gen попробовал сгенерировать chip-descript...
Максим Смирнов
2
я не магистр хаскеля, но разве не может лейзи тип конвертнуться в не-лейзи запросив вычисление содержимого прям при инициализации?
deadgnom32 λ madao
100
Hello VIC team, I had previously used the “wallet.tomochain.com” with a ledger connection. Unfortunately, the site is no longer accessible and the ledger account is not visibl...
carpe noctem
7
здравствуйте. совершаю вот такую вещь: strcpy(line, (char)current_number); где current number — неподписанный шорт, line — массив чаров. ругань следующая: main.c:29:30: error...
Roberto's Ширгозиев
13
@MrMiscipitlick А можешь макрос написать, который будет вычислять смещение относительно переданных меток? Просто .label1-.label2, и вернуть значение.
КТ315
35
А еще в перле можно уже @arr1 + @arr2?
Sergei Zhmylove
53
Карта сайта