Похожие чаты

Why not just throw and error and i catch it?

15 ответов

12 просмотров

That's how mistakes are made when handling errors

so this... try { f := OpenFile() try { f.Write("foobar") } catch { log.Error("write failed") } } catch { log.Error("open failed") } is easier to you than this? f, err := OpenFile() if err != nil { log.Error("open failed") return } if _, err := f.Write(); err != nil { log.Error("write failed") }

Ghazwan-Aliesh Автор вопроса
Codexetreme
That's how mistakes are made when handling errors

Maybe but if we agree on some interface for the thrown error (error code or something) we can have much less code doing more. I get it that go make it easier to recognize the origin of the error that way but it does affect amount of code I am writing as a developer.

Codexetreme
This is not a good example imo

it's not, sure, but still, try-catch is a very ugly construct IMHO

Ghazwan-Aliesh Автор вопроса
Roman Sharkov
so this... try { f := OpenFile() try { f....

The example u gave for traditional approach is kinda unfair imo. if all the functions that might throw and error followed a similar pattern in the error they throw, I will have one try catch.

Ghazwan Aliesh
The example u gave for traditional approach is kin...

how do you determine which Write call failed without having separate try-catch blocks?

Ghazwan-Aliesh Автор вопроса
Codexetreme
And precisely why try catch is dangerous

yeah maybe go is less evil that way now that i think about it. i am just not used to 20 lines functions i guess 😝

Ghazwan-Aliesh Автор вопроса
Roman Sharkov
how do you determine which Write call failed witho...

Well in most cases I won't care as long as the error thrown provides enough data about itself. let's say a register user function that calls: validation method, database method. if both method will throw the error with a message and code in it, I will just want to return it. Idc where it failed.

Ghazwan Aliesh
Well in most cases I won't care as long as the err...

what if they don't throw any codes? (happens a lot actually)

Ghazwan-Aliesh Автор вопроса
Roman Sharkov
what if they don't throw any codes? (happens a lot...

then the methods are badly implemented, which i realize is what go is trying to protect u from doing.

Roman Sharkov
so this... try { f := OpenFile() try { f....

If you use try catch as if err.. are terrible, if you use in smarter way are very elegant. IMO in several situation go is verbose in error handling, some piece of code I wrote there is more error handling boilerplate than code logic. With try catch, used in the proper way (not as in this example) the whole solution could be more readable and compact. Nevertheless the go error handling has other advantages

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

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

Hi there everyone Is there anyone who have not started hamster bot yet? I need only one, I'll be glad if you do this for me DM if you haven't yet
Mehrshad
53
Да и не жалко вроде как, подумаешь, обсудить другой дистр... Только есть три момента: 1) такие разговоры постоянно норовят свалиться в обоюдные оскорбления и страшные холивары...
Dan (つ•̀ᴥ•́)つ
24
why some site like google has separate page for username/email and password?
Mr Thieves
21
Ребят здрасте, а кто нибудь сталкивался с тем что линукс не видел видюху радеон?
Albert
26
Может быть небольшое отступление, но я тут решил обратить внимание на то, сколько весит хелловорлд на с++... Зачем он весит почти 250 Кб? У меня оконное приложение на фасме ве...
The Bird of Hermes
14
Here I have summarized 6 of the BEST Tap-Tap Creations and Claims.  Suitable for those who are just learning or lazy to do assignments hahaha.  😼🤙 ‼️Don't skip all of this 1...
Alex H.K🇮🇩
1
@Dreamer_0x01 @helgispbru @Ambrion Разговор шёл об уязвимости. Меня беспокоит именно она. Все прочие вопросы, а равно и жизненная мудрость - пока в сторону :) Так вот сам ...
Андрей [aharito] Харитонов
5
А как старый хаскел с новым стыковать ? потому как тут работает https://play.haskell.org/saved/C3xpMzcd, а вот тут https://stepik.org/lesson/7602/step/9?unit=1473 нет ошибка C...
Fedor
131
Всем привет ! Перешел недавно с Mojave на Catalin'у , в тч и на OpenCore ... Вопрос такой ... Как избавиться от красного бейджа на "настройках" со втюхиванием поставить Monter...
Maxzim Flyper
9
What do you wanna learn?
Malware ( DM = BLOCK )
12
Карта сайта