9 ms·
I can't get it why people would prefer to add "?" to everything instead of just having exceptions which automate that behavior. In the bad old days of C there
by PaulHoule 4y ago
I can't get it why people would prefer to add "?" to everything instead of just having exceptions which automate that behavior.
In the bad old days of C there were two kinds of programs: programs without correct error handling, and programs where half the loc are unhappy paths that do what exceptions do... with a huge amount of work.
Today people are repeating the same mistakes of the past, putting a "?" on everything is a lot better than what you had to do in C, but why do that when you can just use a language with exceptions?
It is like somebody showed cavemen fire (exceptions) and they decided it wasn't worth anything and went to go screw around with other things.
- marcosdumay 4y ago> It is like somebody showed cavemen fire (exceptions) and they decided it wasn't worth anything Oh, it absolutely can not be that the Rust way is more powerful and you didn't understand it yet. No way. It's all those other people that don't understand the old concept that almost all of them know.
- jeremychone 4y agoAfter a couple of years of coding Rust, I found the error system, including the ?, well thought out. It is explicit and clear that the error is or maps to the function return error. The only thing is that Rust rightfully uses the ? to return early system on option as well, which removed the ability to have None coalescing with "?". This was the right choice from a language point of view, but I wish there would be a None coalescing syntax in Rust.
- nemothekid 4y agoI prefer having extra work done writing code (adding "?") than having to do extra work reading code. Exceptions are functionally invisible control flow; it isn't clear to the reader that a function may blow up if the exceptions are unhandled.
- jb1991 4y agoIn Swift, at least, the possibility that a function can throw must be marked as part of its signature, and the exception cannot be ignored if it is thrown so the call requires explicit syntax as well, so there is no way to miss that something could "blow up" when reading the code.
- eunoia 4y agoIt's a little old at this point, but I find the Swift Error Handling Rationale design doc to be absolutely fascinating. It cites other language’s error handling paradigms (including Rust) if you're curious: https://apple-swift.readthedocs.io/en/latest/ErrorHandlingRationale.html https://apple-swift.readthedocs.io/en/latest/ErrorHandlingRa...
- jb1991 4y agoFascinating, looking forward to reading this later today! Have used a handful of languages over the years, and I don’t have any academic perspective in different error handling techniques, but there’s no doubt that the way swift does it feels particularly natural, safe, but still gets out of your way. I love all the options for handling errors in a meaningful way.
- Jensson 4y agoIn Java functions declares Exceptions in its type signature, so it does all of that automatically. Then you get a compile error if you don't handle it in the function, or you need to declare the function throws it, so it is type safe. Note that people now consider that as a mistake, people prefer having Exceptions be hidden instead of explicit and requiring handling like that.
- newZWhoDis 4y ago> Note that people now consider that as a mistake, people prefer having Exceptions be hidden instead of explicit and requiring handling like that. What people? Please tell me where they’re at so I can tell them they are wrong (lol) But seriously, I could not disagree more.
- lenkite 4y agoThe designers of the Java functional and stream library for one. None of the functional contracts have throws. So you are forced to have un-checked exceptions for everything, unless you want a truly mind-boggling amount of try-catch everywhere which will rapidly exceed your normal code by factor of 2x-3x.
- mike_hearn 4y agoIn Java, yes. Note that the JVM doesn't enforce checked exceptions. It's a language level thing. So in Kotlin for example, where all exceptions are unchecked, you can use the streams library without needing try/catch.
- PaulHoule 4y ago... or you can just use a sane FP library like https://github.com/paulhoule/pidove https://github.com/paulhoule/pidove Some people don't like the Lispy signatures so I did start coding up a version with with a fluent interface but didn't quite finish. Overall I would say the implementation of lambdas and method references in Java 8 was genius, but the stream library was a big mistake. Part of it is that has this cumbersome API that in principle would let it optimize query execution by looking at the pipeline as a whole but doesn't really take advantage of it.
- taeric 4y agoI get where you are coming from, but imagine if every other "to the human" process description we had was done this way. I actually think this would be a fun one. How to make scrambled eggs, but where all failure cases are covered. Would be the "Hal fixes a lightbulb" in prose.
- sowbug 4y agoThat gets to the original promise of computers, doesn't it? That they'd perform repetitive tasks quickly and reliably. Meanwhile, every time I make scrambled eggs, there is a small but very real chance that my house burns down. And we accept this because to err is human.
- taeric 4y agoSorta? But a lot can be packed away in "other directions." Most recipes, for example, assume that setup/teardown is intrinsic to the kitchen. As such, to know the procedures to do those things, you would look somewhere else. That is, you aren't accepting a risk that things will go wrong. You have moved what to do about many exceptions to somewhere else.
- wvenable 4y agoAssume all functions can throw and there is no extra work reading. A function that has no possibility of error is so uninteresting in the context of error handling. Furthermore, handling errors has little to do with where the error is actually caused. In general, you can only do two things with errors: log and kill the operation or retry the operation. Neither of these has anything to do with the leaf function 20 items down in the stack that actually made the network call that failed.
- sanderjd 4y agoWhat you're describing here are unchecked exceptions, which Rust has in the form of panic. There are other kinds of errors that can be handled closer to the point where they occur.
- erik_seaberg 4y agoWe have to be deliberate about where we retry, and how quickly. It’s all too easy for layers to create a death ray of n factorial requests.
- nemothekid 4y agoIf I am in the business of writing robust code; then "assuming all functions can throw" means at the very least forcing every function call to be surrounded by a try/catch block? It almost always make sense to handle an error locally if you can; for example if I want to retry the operation (let's say I'm writing a distributed database client), it may make sense for me to retry another node rather than unwinding to the application level that has now lost all context. >A function that has no possibility of error is so uninteresting that focusing on that is the wrong thing. I spend a lot of time debugging errors in code that has 0% chance of failing. It tends to involve a lot of matrix math. This isn't something you can say is universally true especially given all the hype around AI now.
- quietbritishjim 4y ago> It almost always make sense to handle an error locally if you can This is highly presumptuous. I have written many programs that did not need to handle errors locally, and so exception handlers were only at the very top level (or, actually, just below the top-level usually - but the point is that there were generally few and I had flexibility to decide where to put them). Perhaps you and I write very different applications. But the fact remains that the "almost always" in your statement doesn't hold. Alternatively line of reasoning: if this was always true then there would be little point to Rust's ? as it would be so rarely used.
- PaulHoule 4y agoExceptions always work the same way. You learn how to read code with exceptions pretty quickly.
- frodowtf 4y agoHow does an explicit raise operator like '?' work any different than that? You can learn how to read it pretty quickly.
- einpoklum 4y agoYou may prefer that, but everyone else who has to read your code - doesn't. Yours is an approach which is likely to ensure your code is discarded and has to be rewritten relatively quickly.
- adamnemecek 4y agoThey are not the same. Errors force you to explicitly handle unexpected conditions. Exceptions don't. And "?" is for making error handling not take up half of loc. Read up on how exceptions work in C++ implementation-wise. It's not pretty.
- PaulHoule 4y agoThat's C++. It puts the C in Cthulhu.
- saurik 4y agoThat's the problem, though, right? 99.999% of the time you absolutely should not be "handling" an error: you should merely propagate it so it gets closer to code that has actual intent. Languages that force you to try to "handle" errors--which includes Java, due to their botched concept of checked exceptions--both encourage the wrong behavior in the developer and cause the code to be littered with boilerplate to implement the propagation manually. Meanwhile, they manage to encode the concept of "can fail" into not merely the type signature of a function but into the syntax used to access it, when--like other monadic behaviors, including "requires scoped allocation"--this is the kind of thing you tend to need to refactor into a codebase at a later time: instead, the code should always be typed as if everything can fail and everything can allocate (not just memory, but any resource); languages that get this right--such as C++ and Python--thereby deserve their stickiness.
- veqq 4y ago> you absolutely should not be "handling" an error: you should merely propagate it so it gets closer to code that has actual intent Why?! There are 2 types of errors: - an error in your program logic, which you need to fix - an error from something out of your control (network down, disc errors, faulty input... Which you certainly must handle What's the alternative? Let errors trigger undefined behavior and corrupt your DB? Not pretty.
- jiggawatts 4y agoExceptions are not "undefined" behaviour, and they don't "corrupt the database". On the contrary, they're very often used to abort database transactions cleanly, even in complex chains of deeply nested function calls. What people mean by "not handling errors" is that the Visual Basic style of "On Error Resume Next" is a terrible, terrible thing to do. The equivalent in modern languages is a try-catch block in the middle of a stack of function calls 200 deep. That function likely has no idea what the context before it is. Is it being called from a CLI? A kernel module? A web server? Who knows! Just yesterday I had to deal with legacy code that made this mistake, and now it's going to cause a multi-day problem for several people. It's a ASP.NET HTTP authentication module that simply swallows exceptions during authentication (e.g.: "Can't decrypt cookie"), doing essentially nothing. When deployed "wrong" (e.g.: encryption key is invalid) it just gets stuck in a redirect loop. The authentication redirects back with a cookie, it is silently ignored, then it redirects to the authentication page which already has a cookie so it redirects back, and so on. There is nothing in the logs. No exceptions bubble up to the APM or the log analytics systems. The result is HTTP 200 OK as far as the eye can see, but the entire app is broken and we don't even know where or why exactly. That's not even mentioning the security risks of silently discarding authentication-related errors! This is what people mean by don't "handle" errors. Middleware or random libraries should never catch exceptions. It's fine if they wrap a large variety of exception types in a better type, but even then it is important to preserve the inner exception for troubleshooting. I've had to tell every developer this that I've worked with recently as a cloud engineer. Stop trying to be "nice" by catching exceptions. Exceptions are not nice by definition and ignoring that reality won't help anyone.
- taeric 4y ago> and programs where half the loc are unhappy paths that do what exceptions do... with a huge amount of work. This made me laugh harder than makes sense. I'm sure I've been guilty of doing said code, as well.
- jakelazaroff 4y agoExceptions come with their own weirdness. Usually, if you want to handle an exception, you need to wrap the code that could generate it in a block, which means any variables declared there won't be available in the parent scope. I'd much rather have the ability to just write normal code and deal with the error on the spot, along with some syntactic sugar (such as "?") to return that error to the caller.
- deleted 4y ago[deleted]
- larusso 4y agoHow would an exception automate the behavior of „?“? What ? does in rust is to unwrap the result check if it is err and return from the function with an error result. On top of that it will auto-convert the error type (if the type has the from/into traits implemented) So it would do: try { //the code that may fail } catch (error) { //do we just throw the same error? //or convert the exception to a custom other exception } If I see an API that throws me an low level exception without context I go mad. Like an file not found exception etc when executing an API that does multiple file IO operations.
- pclmulqdq 4y agoThere's some subtlety here: 1. Exceptions have very high performance costs (equivalent to a longjmp which is very slow), so if you expect to have exceptional cases, it's probably a lot more efficient to not use exceptions. 2. Exceptions break the linear flow of the code when you read it, so now you have to read a lot more code to figure out what the exception paths are and where and how they are handled.
- planede 4y ago> Exceptions have very high performance costs On the sad path. On the happy path they are faster than explicit error checking.
- pclmulqdq 4y agoKind of yes, and kind of no. On the happy path, if errors are very very rare, the check is also basically free thanks to branch prediction. They start to cost something when you start to add a higher frequency of errors, which incidentally is where exceptions cost a lot more.
- mike_hearn 4y agoThe cost is higher because of all the branches that are scattered everywhere to check return codes. With exceptions there's a check at the place the error is thrown, but that's inevitable. There aren't checks scattered throughout the rest of the code, which would otherwise reduce icache utilization.
- pclmulqdq 4y agoArguing about icache utilization is a little silly here - the code will be laid out for you as though the branches are not taken (or you should force it to do so). In that case, the only "waste" of icache is the CMP and JMP, an additional 4-8 bytes per return, and literally 0 cycles. When you do take an error, each RET takes you 1 cycle, plus the 10-15 cycle mispredict for the CMP+JMP because there's a stack engine in the CPU that tells you the address to return to. It's counterintuitive that doing "a lot" of things is cheaper than doing fewer things, but it's true. In comparison, an exception involves taking the one control flow break to some cold control code (maybe page faulting), figuring out where to go using a jump table (slow), restoring the old state from that context (slow), figuring out the type of the thrown object (in many languages, also slow), and then handling accordingly. Each of these steps can easily take 100+ cycles, and may be more. The math does not work out in favor of exceptions. Neither do the benchmarks in most cases. You do 1 slow thing to avoid doing 20 things that are trivially fast.
- chomp 4y agoIt's mostly philosophical, are you fine with blowing up with an exception, or would you rather have your functions return known values for the unhappy path? I personally like exceptions in exceptional cases, but much rather having functions with explicit contracts (e.g. "this will return either True or False in all input cases", not "this will return either True, or Exception in all cases when $foo doesn't exist in the database, and woe unto the programmer that forgets to catch this.")
- girvo 4y agoNim handles that with the {.raises: [].} pragma and the effect system, which is quite a neat approach. It’s like opt-in checked exceptions, but with much nicer ergonomics than Java used to have
- duped 4y agofn foo () -> Result<(), E1> { .. } fn bar () -> Result<(), E2> { foo()?; } This requires `bar` to have a function signature that notes it may error, `E2` must implement `From<E1>`, and the caller of `bar` must use the result or explicitly silence the warning. Meaning if a program creates a Result the error must be handled - you can't silently let errors bubble up through the call stack. `Result` implements some common combinators like `.ok()` to convert to `Option`, `map`, `map_err`, `or_else`, etc to reflect the common cases of error handling. And finally, since Result doesn't require non-local control flow like exceptions you know that `drop` will run as the functions return back up the callstack. And if you want to use Result like exceptions... you can. But you can't hide it from callers, and callers are still free to handle them elegantly.
- Larrikin 4y agoDespite what CS and SE classes try to drill into you, null results or failure cases are nearly always better handled right when they happen instead of passing them up with layers of exception handling. Log it, pass null up, and just immediately handle it. Fail early and none of the rest of the function matters. Even types of exceptions are rarely useful results outside of reading the logs or sometimes in libraries outside of your control.
- 8note 4y agoThe most important considerations for errors is whether they can be retried, and who needs to change something to fix it. The types can be useful for communicating this
- za3faran 4y agoHow do you handle a DB connection time out in your stack? You can log it and retry, eventually the entire call must be terminated though, and the quickest way is through exception propagation.
- jeddy3 4y agoIMHO both exceptions and error handling in Rust (and others) have their upsides and downsides. Personally, I much prefer Rusts solution, being both more up front and at the same time more terse. The metaphor is kinda stupid though, the "cavemen" in our scenario knows very well that exceptions exist.
- jbellis 4y agoError handling in Rust is actually a lot worse than you think. In fact it may be the single worst aspect of the language. Fundamentally it is difficult to impossible to fix bugs without knowing what code caused it. Java-style exceptions give you a backtrace for free, which is a huge head start. With Rust you have to do a lot of manual plumbing with something like error_stack to get similar functionality, out-of-the-box Errs do NOT capture this. Far more productive to work in an environment that does the right thing "for free" vs having to do it manually.
- hobofan 4y ago> Java-style exceptions give you a backtrace for free, which is a huge head start. With Rust you have to do a lot of manual plumbing with something like error_stack to get similar functionality With crates like anyhow and eyre you also get backtraces "for free" nowadays, without needing to do manual plumbing (all you need to do is toggle on a feature flag).
- dalyons 4y agoUgh that’s one of the worst parts of go too. Stackless errors are so useless and hard to debug.
- flohofwoe 4y agoThe problem with exceptions isn't the syntax, but the hidden control flow (they are essentially a goto in disguise). Error union return values make a lot more sense, the rest is just syntax sugar details (and that's where opinions differ I guess).
- kcartlidge 4y agoMy two main languages are C# and Go. * C# uses exceptions, and when I code it feels exactly the right choice * Go uses error return values, and when I code it feels exactly the right choice For some reason both feel very much ideal in use. Maybe it is because in each case the language syntax/ethos fits very well with the choice made, and so is frictionless when developing in the flow (and if used properly of course)? Maybe some other reason. Hey ho.
- gpderetta 4y agoExceptions are not a form of gotos, they are both less powerful as they are structured and more powerful (as they are nonlocal). They desugar to continuations, but so does rust option type handling and ?. In fact they are pretty much equivalent. I'm not terribly familiar with either language, but I don't see any particular difference between swift and rust error handling for example, swift will also mark fallible function calls with try, similarly to ? in rust. For what is worth the author of the swift standard library believes that try is a mistake: as most functions can fail in practice it just becomes noise. It might be more useful to mark can't fail regions.
- jstimpfle 4y agoIf you consider the case where you call a function that throws an exception without you expecting it -- then the control flow will skip your code, and this is indeed not very structured, like a goto, and in fact less local than a goto.
- flohofwoe 4y agoI was actually wondering (in Zig, which has a per-statement "try" which is essentially the same as the ? in Rust) whether it also makes sense for whole blocks, which would look a lot like traditional try-catch block in languages with exceptions, e.g. instead of: try may_fail_1(); try may_fail_2(); try may_fail_3(); ...this could be grouped into: try { may_fail_1(); may_fail_2(); may_fail_3(); } ...but would behave exactly the same as the indiviual trys, if any function in the block returns with an error, that same error is passed up to the caller. But I guess that forcing individual trys makes you think harder about handling individual errors than just pushing the responsibility for error handling up the callstack.
- MaulingMonkey 4y agoIn theory, I like exceptions. In practice, I hate them. Few languages statically check exception handling - e.g. Java, and even then only partially - leading to stability-ruining edge cases leaking into production in the most unexpected of places caught only by QA if you're lucky. Exception handling codegen can also be rather atrocious, leading to unavoidable performance degredation when third party middleware throws unavoidable exceptions, even when you do fix the stability bugs. They're also a nasty and reoccuring source of undefined behavior when they unwind past a C ABI boundary, an issue I've encountered in multiple codebases with multiple exception-throwing languages. In my personal experience, programmers are also rather terrible at writing exception-safe code. Result and ? force you to think about - or at least acknowledge - the edge cases. For a throwaway script or small scale easily tested program, that might be a drawback. For MLOC+ codebases where link times alone are sufficient to start impeding testing iteration times, it can be a big help for correctness and stability, while still being relatively lightweight compared to other manual error handling. Finally - Rust has exceptions. They're called panics. They can be configured to abort instead of unwind. This helps set the tone - they're really meant for bugs, and exceptionally exceptional circumstances. They cause all the problems of exceptions, too - unconsidered edge cases, undefined behavior unwinding past C ABIs, the works. Fortunately, it's reasonable in Rust to aim to eliminate all panics but bugs.
- PaulHoule 4y agoSee https://gen5.info/q/2008/07/31/stop-catching-exceptions/ https://gen5.info/q/2008/07/31/stop-catching-exceptions/ and https://gen5.info/q/2008/08/27/what-do-you-do-when-youve-caught-an-exception/ https://gen5.info/q/2008/08/27/what-do-you-do-when-youve-cau... It's very important to minimize the burden of handling errors in code with simple control flow. Frequently I see people try very hard to handle errors with monads in languages like Scala at the micro level and they are so burned out by this that they don't put any effort into handling errors properly at the macro level. If you make the micro level as automatic as you can it is possible devs will address the macro level, and what is necessary at the micro level is not dealing with a crisis that prevents the compiler from building your code, but rather cleaning up the environment consistently in both normal in error conditions and giving the macro level sufficient context for the error that it can do the right thing.
- User23 4y agoExceptions make it considerably harder to reason about state by reading the program text. As the notion that programmers should have some actual understanding of what they write slowly becomes less unfashionable, language features that make understanding code needlessly harder are losing some of their appeal even though they speed up writing the code.
- PaulHoule 4y agoWhat really makes code hard to read is having multiple paths to disentangle. There is one little error deep in the call stack but you have to vandalize the 10 functions above it in the call stack to carefully separate the error and non-error paths -- what's the probability that you will end up cleaning up properly in both paths when it isn't done for you with finally? What's the probability that somebody looking at this code is really going to find the subtle error in the error path or an error in the happy path caused and hidden by the complexity of the unhappy path? I think the first C program I saw was a type-in terminal emulator from Byte magazine around 1985 and I was struck by the akwardness of the error handling in the C stdlib, spent a lot of time looking at the code when I realized the author had "spaced it" at one point such that the error handling was wrong and thought "this sucks" but learned how to write C programs with 3x the LOC because of all the alternate paths I had to put in to handle errors. When I saw exceptions for the first time I felt strongly liberated because I got for free what I was working for so hard in C so I got to spend more time thinking about algorithms, the needs of the customer, things like that.
- Conscat 4y agoExceptions make it difficult to find failure-points in the code. The ? annotates that at its call site, which improves discoverability by a lot and reduces readability by only a little.
- lenkite 4y ago> Exceptions make it difficult to find failure-points in the code My experience doing Java, Go and Rust has been completely the opposite. Exception stack traces in Java are amazingly wonderful things - they exactly pin-point the failure points in the code. The amount of hunting I need to do to find out where something failed in the call stack in Go/Rust is tedious. You need a module/crate for error tracing or you up waddling against a strong current of despair.
- FridgeSeal 4y ago> Java are amazingly wonderful things - they exactly pin-point the failure points in the code. Yes. Once the exception has happened. At runtime. Which is not when I want to be trying to fix things. I’d much rather handle as much as possible statically, knowing that what I push into has every non-panic code path cleanly handled. I’ve never had the equivalent experience with exceptions, it’s always “well I’ve wrapped everything I possibly can in as much try-catch and handling as I possibly can, and oh look, some random piece of code has still thrown some random exception we’ve never seen before”.
- za3faran 4y agoYou still need a top level exception handler in your main loop.
- orthecreedence 4y ago> I can't get it why people would prefer to add "?" to everything instead of just having exceptions which automate that behavior. Exceptions? Which exceptions? How do you know which exceptions you're supposed to be handling and where they come from or when they happen? I prefer the control flow of the program and the exact types of errors I'm handling to be explicit.
- oconnor663 4y agoI mean, ask the C++ community. They've had exceptions forever, but a large chunk of them forbid exceptions in their codebases. I think there's a pretty good rule of thumb in modern systems-ish language design: If Go and Rust and Zig all do a certain thing, that thing is probably a great idea. These languages have very different priorities, but often they overlap.
- ngrilly 4y agoZig, unlike Go and Rust, provides an error return trace showing how the error bubbled up. This is a really interesting idea. https://ziglang.org/documentation/master/#Error-Return-Traces https://ziglang.org/documentation/master/#Error-Return-Trace...
- tbillington 4y agogo and rust both have this, though opt in at each location you're adding context.