this post was submitted on 13 Sep 2024
45 points (100.0% liked)

Programming

423 readers
5 users here now

Welcome to the main community in programming.dev! Feel free to post anything relating to programming here!

Cross posting is strongly encouraged in the instance. If you feel your post or another person's post makes sense in another community cross post into it.

Hope you enjoy the instance!

Rules

Rules

  • Follow the programming.dev instance rules
  • Keep content related to programming in some way
  • If you're posting long videos try to add in some form of tldr for those who don't want to watch videos

Wormhole

Follow the wormhole through a path of communities !webdev@programming.dev



founded 1 year ago
MODERATORS
top 32 comments
sorted by: hot top controversial new old
[–] FizzyOrange@programming.dev 33 points 2 months ago (2 children)

I think I disagree with everything here.

Exceptions Are Much Easier to Work With

Well, they're "easier" in the same way that dynamic typing is easier. It's obviously less work initially just to say "screw it; any error gets caught in main()". But that's short term easiness. In the long term its much more painful because:

  1. You don't know which functions might produce errors, and therefore you don't know where you should be even trying to handle errors. (Checked exceptions are the answer here but they are relatively rarely used in practice.)
  2. Actually handling errors properly often involves responding to errors from individual function calls - at least adding human readable context to them. That is stupidly tedious with exceptions. Every line turns into 5. Sometime it makes the code extremely awkward:
try {
   int& foo = bar();
} catch (...) {
   std::cout << "bar failed, try ...\n";
   return nullopt;
}
foo = 5;

(It actually gets worse than that but I can't think of a good example.)

Over 100× less code! [fewer exception catching in their C++ database than error handling in a Go database]

Well... I'm guessing your codebase is a lot smaller than the other one for a start, and you're comparing with Go which is kind of worst case... But anyway this kind of proves my point! You only actually have proper error handling in 140 places - apparently mostly in tests. In other words you just throw all exceptions to main().

System errors [he's mainly talking about OOM, stack overflow & arithmetic errors like integer overflow]

Kind of a fair point I guess. I dunno how you can reasonably stack overflows without exceptions. But guess what - Rust does have panic!() for that, and you can catch panics. I'd say that's one of the few reasonable cases to use catch_unwind.

Exceptions Lead to Better Error Messages

Hahahahahaha. I dunno if a bare stack trace with NullPointerException counts as a "better error message". Ridiculous.

Exceptions Are More Performant

Sure maybe in error handling microbenchmarks, or particularly extreme examples. In real world code it clearly makes little difference. Certainly not enough to choose an inferior error handling system.

I would say one real reason to prefer exceptions over Result<>s is they are a fair bit easier to debug because you can just break on throw. That's tricky with Result<> because creating a Err is not necessarily an error. At least I have not found a way to "break on Err". You can break on unwrap() but that is usually after the stack has been unwound quite a bit and you lose all context.

[–] BehindTheBarrier@programming.dev 4 points 2 months ago (1 children)

It can be pretty convenient to throw an error and be done with it. I think for some languages like Python, that is pretty much a prefered way to deal with things.

But the entire point of Rust and Result is as you say, to handle the places were things go wrong. To force you to make a choice of what should happen in the error path. It both forces you to see problems you may not be aware of, and handle issues in ways that may not stop the entire execution of your function. And after handling the Result in those cases, you know that beyond that point you are always in a good state. Like most things in Rust, that may involve making decisions about using Result and Option in your structs/functions, and designing your program in ways that force correct use... but that a now problem instead of a later problem when it comes up during runtime.

[–] kersplomp@programming.dev 2 points 2 months ago (1 children)

But the entire point of Rust and Result is... to force you to make a choice of what should happen

Checked exceptions also force you to handle it and take way less boilerplate.

[–] BehindTheBarrier@programming.dev 3 points 2 months ago* (last edited 2 months ago) (1 children)

But nothing is forcing you to check exeptions in most languages, right?

While not checking for exceptions and .unwrap() are pretty much the same, the first one is something you get by not doing anything extra while the latter is entirely a choice that has to be made. I think that is what makes the difference, and in similar ways why for example nullable enabled project in C# is desired over one that is not. You HAVE to check for null, or you can CHOOSE to assume it is not by trying to use the value directly. To me it makes a difference that we can accidentally forget about a possible exception or if we can choose to ignore it. Because problems dealt with early at compile time, are generally better than those that happen at runtime.

[–] kersplomp@programming.dev 1 points 2 months ago (1 children)

I see your concern, but in practice that's not what happens in languages like Java and Python with exceptions. Not checking for exceptions is a choice because everyone knows you need to check in your top-level functions. Forgetting to catch is a problem that only hits newbies.

[–] OmnipotentEntity 5 points 2 months ago (1 children)

A problem that only affects newbies huh?

Let's say that you are writing code intended to be deployed headless in the field, and it should not be allowed to exit in an uncontrolled fashion because there are communications that need to happen with hardware to safely shut them down. You're making a autonomous robot or something.

Using python for this task isn't too out of left field, because one of the major languages of ROS is python, and it's the most common one.

Which of the following python standard library functions can throw, and what do they throw?

bytes, hasattr, len, super, zip

[–] kersplomp@programming.dev 1 points 1 month ago

Too long, didn't read

[–] BatmanAoD@programming.dev 1 points 2 months ago (1 children)

There's also a massive tradeoff for when the error condition actually occurs. If an exception does get thrown and caught, that is comparatively slowwww.

[–] UndercoverUlrikHD@programming.dev 1 points 2 months ago (1 children)

The author pointed out how exceptions are often faster than checking every value. If your functions throws an error often enough that Exception handling noticeably slow down your program, surely you got to take a second look at what you're doing.

[–] BatmanAoD@programming.dev 1 points 2 months ago

It depends what kind of errors you're talking about. Suppose you're implementing retries in a network protocol. You can get errors pretty regularly, and the error handling will be a nontrivial amount of your runtime.

[–] Ephera@lemmy.ml 18 points 2 months ago (1 children)

The guy keeps on picking on Go, which is infamous for having terrible error handling, and then he has the nerve to even pick on the UNIX process return convention, which was designed in the 70s.
The few times he mentions Rust, for whatever reason he keeps on assuming that .unwrap() is the only choice, which's use is decidedly discouraged in production code.

I do think there is room for debate here. But error handling is a hellishly complex topic, with different needs between among others:

  • short- vs. long-running processes
  • API vs. user-facing
  • small vs. big codebase
  • library vs. application code
  • prototyping vs. production phase

And even if you pick out a specific field, the two concepts are not clearly separated.
Error values in Rust usually have backtraces these days, for example (unless you're doing embedded where this isn't possible).
Or Java makes you list exceptions in your function signature (except for unchecked exceptions), so you actually can't just start throwing new exceptions in your little corner without the rest of the codebase knowing.
I find it quite difficult to properly define the differences between the two.

load more comments (1 replies)
[–] aubeynarf@lemmynsfw.com 13 points 2 months ago (3 children)

You have to explicitly check if the return value is an error and propagate it. You write the same boilerplate if (err) return err over and over again, which just litters your code.

That’s only true in crappy languages that have no concept of async workflows, monads, effects systems, etc.

Sad to see that an intentionally weak/limited language like Go is now the counterargument for good modeling of errors.

[–] sping@lemmy.sdf.org 11 points 2 months ago

I naively thought it I may as well take a job using Go, as learning a new language is broadening, and some people like it, so lets find out first hand... I knew it was a questionable choice, looking at how Go adoption tailed off a while ago.

Turns out I hate Go. Sure it's better than C but that's a very low bar, and C was never a good alternative choice for the use cases I'm encountering. I'm probably suffering from a codebase of bad Go, but holy shit it's painful. So much silent propagation of errors up the stack so you never know where the origin of the error was. So very much boilerplate to expand simple activities into long unreadable functions. Various Go problems I've hit can be ameliorated if you "don't do it like that", but in the real world people "do it like that" all the time.

I'm really starting to feel like there are a lot of people in the company I've joined who like to keep their world obtuse and convoluted for job security.

[–] matcha_addict@lemy.lol 4 points 2 months ago (2 children)

Can you please demonstrate how async workflows and monads resolve this issue?

Wouldn't effect systems still be considered exceptions, but handled differently?

[–] sukhmel@programming.dev 7 points 2 months ago

I don't know the answer to your question, but I think that what is needed is just a bit of syntactic sugar, e.g. Rust has ? for returning compatible errors without looking into them. That seems to be powered by Try trait, that may be a monad, but I am not fluent enough to check if it formally is.

load more comments (1 replies)
[–] lysdexic@programming.dev 2 points 2 months ago

That’s only true in crappy languages that have no concept of async workflows, monads, effects systems, etc.

You don't even need to sit on your ass and wait for these data types to be added to standard libraries. There are countless libraries that support those, and even if that is somehow not an option it's trivial to roll your own.

[–] thingsiplay 13 points 2 months ago (1 children)

My anecdotal experience is that Rust code, for example, has more calls to unwrap than I’d like. The problem here is that simply unwrapping results will crash the program on errors that could have been a user-visible error message with exceptions.

unwrap() is explicitly not handling the error in a Result type. If you must do this, then at least use except(), to unwrap the code but with an error message if program crashes. Its the equivalent of having Exceptions and then not handling that exception. Therefore your critique is not valid here.

One problem with Exceptions is, you never know what code your function or library calls that can produce an exception. It's not encoded in the type system or signature of the function. So you need to pray and try catch all possible exceptions (I look at this from Pythons perspective), if you don't want a Catch..All, which then you wouldn't know what error this actually is. And you still don't know where this error came from or happened in the code, how deep in the function call chain? Instead Errors as Values means its encoded in type system and you can directly see what errors the function can cause and (in Rusts case) you must handle the error, otherwise program won't compile. You don't need to handle anything else in this context. Compiler ensures that all possible errors are handled (again within context of our discussion). Vast improvement!

[–] sukhmel@programming.dev 4 points 2 months ago (1 children)

you never know what code your function or library calls that can produce an exception

As far as I remember, there were several attempts at introducing exceptions into type system, and all have failed to a various degree. C++ abandoned the idea completely, Java has a half-assed exception signature where you can always throw an unexpected exception if it's runtime exception, mist likely there were other cases, too.

So yeah, exception as part of explicit function signature is a vast improvement, I completely agree

[–] thingsiplay 1 points 2 months ago (1 children)

So yeah, exception as part of explicit function signature is a vast improvement, I completely agree

Hmm, I'm not sure if you are being sarcastic. In my reply I didn't meant encoding Exceptions into Type system. Is this a type and you probably meant "Error Types as part of" instead "exception as part of"?

Honestly I don't know how Exceptions as part of type system would even look like. Because each function call in a chain would need to have all information from previous function call, otherwise that information gets lost to the next caller. The problem is the hierarchy of function and method calls. Somewhere some objects and functions can be edited to Throw a new Exception, that is not handled through the entire chain. And for the higher function caller, there is 0% way of knowing that (through code, besides documentation off course).

[–] sukhmel@programming.dev 3 points 2 months ago (1 children)

Yeah, I shaped my words poorly. What I meant is that errors are sort of equivalent to exceptions, but errors are first class citizens of type system, and this is an improvement over exceptions being kind of independent of type

[–] thingsiplay 2 points 2 months ago

Ah it was intentional and now I see how it was meant. It makes perfectly sense, it was just not clear before. :-) Human language and interpreter is not as precise like programming language.^^

[–] mox@lemmy.sdf.org 7 points 2 months ago (1 children)

It would be nice to include Zig's approach in the comparison. I've only just begun learning it, but the syntax seems pretty elegant from what I've seen so far.

Upvoting not because I share author's preference, but because I'm interested in reading other people's perspectives on the topic.

[–] thingsiplay 2 points 2 months ago

Read my reply with a handful of sea salt. I just read tutorials and documentation a bit and did Hello World.

Zig is pretty cool too! It can run C code directly just like C++ does (I think), kind of drop in replacement. From my reading so far, Error Handling is kind of a marriage between Go's and Rust's Error handling. Actually pretty cool. It has Error Types, but is kept relatively simple and doesn't force to do all the stuff. It has Try and Catch keywords to handle errors elegantly, but don't be fooled, this has nothing to do with Try...Catch blocks for Exceptions. Zigs Try and Catch are more like Rusts Result type handling, at least from what I read so far.

I lean more towards Zig than Go, but it still has not reached stable 1.0 release.

[–] DirigibleProtein@aussie.zone 6 points 2 months ago

Memory isn’t infinite, CPUs can’t process all integers, and Santa isn’t real

Wait, what? Need a spoiler tag.

[–] ExperimentalGuy@programming.dev 6 points 2 months ago

The article made a few good points, but a good amount of it was conjecture. I liked the part about comparing the two functions and showing that exceptions are faster but I think a big thing he's not getting is readability. Even in the functions he showed, you can directly see that the one using std::expected has the happy path and error path directly in the function signature, whereas the exception one doesn't.

As for the "error kind" trap he was talking about, that definitely exists, but ignores the fact that you can also get this same kind of error from exceptions. I've definitely gotten exceptions that I didn't understand from Python or Java libraries, but it's not a problem with exceptions but a problem with how they're shown. If there's nothing to tell me that I should have thought of that error, it shouldn't be an expectation for a dev to have thought of it.

They both have their place. I just recently discovered a bug in lemmy bot I wrote where the lemmy API module will raise an Exception if login fails (response status code != 200), which feels extremely out of place, as the error/status code do matter in that case.

Other times exceptions make more sense as Phillip pointed out. It's ~~easier~~ faster to ask for forgiveness than permission after all.

[–] magic_lobster_party@fedia.io 3 points 2 months ago

I didn’t read everything, but I mostly agree with the author, especially on this point:

While you can definitely abuse exceptions, functional-style error values are not a one-size-fits-all solution.

There are time and place for both. I think exceptions are good for bigger errors. Like database connection errors. Things that shouldn’t happen without any easy backup plan. Those errors might need to be escalated as high as possible where proper action can be made (like resetting the database connection and everything relying on it).

Functional style is great for smaller stuff. Like key not found in hash maps. In many cases there might be good defaults that can be used instead.

[–] Kissaki@programming.dev 2 points 2 months ago

Does the performance cost of error checking/result types they discovered in C++ apply to languages that have native result and option types like Rust?

I would hope they were able to find efficient, performant implementations, and that branch prediction picks the expected non-error branch in most cases.

[–] Kissaki@programming.dev 1 points 2 months ago

They make valid points, and maybe it makes sense to always prefer them in their context.

I don't think exceptions always lead to better error handling and messages though. It depends on what you're handling.

A huge bin of exception is detailed and has a lot of info, but often lacks context and concise, obvious error messages. When you catch in outer code, and then have a "inaccessible resource" exception, it tells you nothing. You have to go through the stack trace and analyze which cases could be covered.

If explicit errors don't lead to good handling I don't think you can expect good exception throwing either. Both solutions need adequate design and implementation to be good.

Having a top-level (in their server context for one request or connection) that handles and discards one context while the program continues to run for others is certainly simple. Not having to propagate errors simplifies the code. But it also hides error states and possibilities across the entire stack between outer catch and deep possible throw.

In my (C#) projects I typically make conscious decisions between error states and results and exceptional exceptions where basic assumptions or programming errors exist.

[–] kersplomp@programming.dev 1 points 2 months ago

Oof, some of these comments. Sorry on behalf of the edge lords, OP.