Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> But here the name actually matters. They're called "panic"s, not exceptions.

But crucially that doesn't at all affect what they do, how they do it, or what it means for programmers needing to write code.

Even if you never write "panic", or never write "recover", your code still needs to be exception safe.

> When you panic, you signal a fatal error that should ideally terminate the program

The "should ideally" is the flaw in this plan. If your code could EVER be called within an HTTP handler, or from a String() function, then you NEED to write it exception safe.

This code is a time bomb:

    […]
    foo.Lock()
    something()
    foo.Unlock()
    […]
To function correctly it must be:

    […]
    func() {
      foo.Lock()
      defer foo.Unlock()
      something()
    }()
    […]
> You shouldn't care about closing files or freeing memory

But I do care about deleting tempfiles, unlocking mutexes, closing channels, etc…, because you do need to do that.

And this is the Go authors themselves showing off panics, saying "there's a bug" if the file isn't closed:

https://go.dev/blog/defer-panic-and-recover

Go authors explicitly say you should NOT count on finalizers for correct behaviour. So no, close your files.

> well-written Go does not panic

But sometimes it does. And if your code is not exception safe then you turn a safe problem into, essentially, undefined behaviour.

> and if it does, execution will end very soon.

Nope, not if panicing in an HTTP handler. If these two HUGE examples I've given you didn't exist then I would likely agree with you.

But I'm going to declare knorker's law: Every piece of code ever written will at some point be called from an HTTP handler.

> A panic in a String() method is just bad code, don't do it.

That's too much "just don't write bugs". Modern languages are supposed to be safe, no?

> in C++ you can reasonable expect an exception anywhere

Yes, just like in Go you never know in what context your code will run in the future. Which means that in both Go and C++ you need to write exception-safe code even if you never throw or catch exceptions.

> [C++ exception for] IO failures […in idiomatic C++]

Oh? The standard library doesn't do this, right? What makes you say that's idiomatic C++?

Idiomatic Java, sure, but Java is just crazy about exceptions for everything.

> [C++ exceptions for] invalid states [… in idiomatic C++]

Idiomatic Go also calls for panic for the "can't happen" case.

> other errors that should be expected in the execution of a program all throw exceptions in idiomatic C++.

What makes you say this is idiomatic C++?

I've seen Go code that does it too, but that doesn't make it idiomatic Go.

Does the C++ standard library do this? The closest thing I can think of is std::bad_alloc on OOM, but then again Go panics then too.



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: