Exceptions

To the old codemonkeys here: how useful/common is using exceptions?
Everyone I talk to seem to hate them/find them useless.

Attached: exceptions.jpg (1164x731, 61K)

Other urls found in this thread:

gigamonkeys.com/book/beyond-exception-handling-conditions-and-restarts.html
twitter.com/NSFWRedditGif

you didn't specify a language

Well, I was asking more in general terms, but if language is important let's assume Java or C++.

well exceptions in a language like C++ really just suck.
they have a runtime cost and they make programming harder not easier imo.

>laughs in tagged union

In Java, exceptions are a must as some are checked meaning you have to at least throw them. They make your life a lot easier especially when you need to verify program input and don't feel like running strings through a thousand regexes just to make sure the program won't break. Do they have effeciency drawbacks? Yes, but they're negligable and if you're using Java, you probably don't care that strongly about efficiency anyway.

In C++, they're not as useful for a few reasons. Sometimes it's good to use them, but it's kind of pointless to throw an arbitrary exception manually in a try block most times. You'd be better off just using a Boolean flag in a loop or something like that.

Not to mention you can put resources in a try statement, and they'll automatically release when the block is done.

exceptions are for things that shouldn't happen (they are exceptional), they should be used to protect against unexpected circumstances. they should not be used to describe error conditions that are a normal part of program processing (can't find user input file, invalid number input etc). NEVER use them as a control flow mechanism for the normal operation of your program. Some frameworks use exception the wrong way, pajeets at microsoft use them the wrong way. don't use their shitty frameworks and software.

So you have to insert a lot of if/then/else to handle failures, instead of letting the compiler doing the menial work.

What do people use instead of exception to catch errors? Java programmer here.

There are a couple different approaches
>Error codes
C programmers use this a lot. You use the return value of a function to indicate if a function failed. You need to test that return value with an if condition before doing anything else.
>Multiple return values
Go programmers use this one. You return a value and an error simultaneously, and test the error before using the value. Not much different to error codes.
>errno
Also used in C. You have a global or thread-local variable and check it after calling a function to see if the function failed. Pretty much the worst way to do error handling IMO.
>Sum types.
Functions return either a value or and error. You need to destructure the return value using a technique like pattern matching before you can use the value. This sounds pretty awkward, but most languages that use this method have a mechanism like monads that make it extremely terse to manipulate value-or-error results without writing boilerplate.

not him, but thanks.

NodeJS' callbacks heavily rely on the multiple return types as well. A callback usually gets the arguments (error, value)

I use exceptions in my JavaScript for catching errors on my asynchronous returned promises.
When I'm connecting to my databases in my app calls I have a wrapper function that puts all my database io interactions in a try catch finally block. That's what annontations are for. To get rid of the pain of boiler plate code.

Windows ecosystem tend to use HRESULT, which is a 32-bit signed int. Negative values constitute an error, 0 is generic success, and positive values are for success-with-caveats.

Thing is, in C++ the recommended idiom is to have the lifespan of an object match the time the class invariant is to be maintained, and the constructor is supposed to set up the invariant. Returning normally from a constructor if the invariant couldn't be established creates an object in an invalid state, which is not really what you're supposed to do in C++, and you can only really avoid that by throwing an exception.

If I'm not mistaken, the error and value arguments are both functions that are called with the result of the computation. That would make it more like a sum type in continuation-passing style.

That's why exceptions were first added to C++, after all.

assert

In python you base your whole program on being an exception that it might work. I'm not even kidding. Dynamic typing for variables and types for everything possible, make that basically mandatory.

Read about the legendary "how do I check if a variable is integer" problem.

>Everyone I talk to seem to hate them/find them useless.
the whole point of exceptions is not to handle errors explicitly, not to manually pass up error codes.

you should stop handle errors and let exceptions bubble up until you catch them at some very high level. most errors are unrecoverable anyway and only requires to write log message or something.

and that's why checked exceptions is a terrible idea.

Might as well make all your types dynamic if your philosophy is "it's the caller's problem, not mine"
Catch me using descriptive interfaces any day.

Sometimes I get into a dilemma with following this pattern. Suppose I've got an input stream and want to create an object to represent the data. I could pass the stream to the constructor, but then if the stream was malformed I'd have to throw an exception, and people say that's not supposed to be done in an inner loop.
Or you check the format in an external function and have the class constructor just assume that's ok - but that's bad because the class is supposed to defend its own validity. Or have it format checked in an external function and rechecked by the constructor, but that's a blatant duplication effort and wasted cpu time.

Handling exceptions is an anti-pattern. Let them rewind the stack and exit the program if you encounter them. Even having the possibility to encounter them means you fucked up.

Might as well just call abort on errors if that's your philosophy.

you can define your error conditions with types or enums if you want the compiler to pick up problems. there is no advantage here with exceptions (in fact there is probably a performance disadvantage with exceptions depending on implementation, stack unwinding). your argument is invalid.

if exceptions are rarely used (I'm talking 1 in a thousand cases) then using them is cheaper then testing all your error conditions

There is a great advantage, doing nothing will properly unwknd, release and abort. Without exceptions you must be sure that errors are handled in each frame.

Checked Exceptions in Java are terrible. They turn user code into try/catch spaghetti. There's a reason why C# doesn't have them. There's a reason why frameworks like Spring don't use them.

In every Java library I write, I convert all checked Exceptions to unchecked RuntimeExceptions and just use the checked Exception as the cause. Cleaner code, preserved stack trace if something goes wrong. I put all potential Runtume Exceptions a function can throw in the Java doc comment.

It's literally in my definition of done for my junior engineers. "No "throws" declarations in public methods". I will block a pull request for using them. They're awful and shouldn't exist.

so what would even be an exception? ant stuck in your cpu?

you are misunderstanding, i am saying programmer defined errors, or errors which are handled by the application should be defined with types or enums, exceptional cases should be exceptions (perhaps with one or two high level handlers (depending on the app) as another user said). program flow should not be driven by exceptions. the amount of performance issues I have fixed with dumb cunts using exceptions in performance critical code... jeez..

not to mention the try catch spaghetti. it is the demarcation between exception usage and normal program flow that many programmers seem to not understand. try catch and custom exceptions should be used sparingly and some kind of usage policy should be made for the project by whoever is leading.

Checking the filesystem and sanitizing user input are not performance critical operations. Likewise, it would be utterly pointless to use exceptions only to signal programmer errors.

thats a different issue.

What is a different issue?

there is more than one reason to not use exceptions and in the case of filesystem and user input sanitation it is not about performance.

Okay, what is it?

unless you are using checked exception then calling code will not be forced to handle errors. checked exceptions cause maintenance problems. A container type for the error + any returned data (a maybe or either), ensures the error is handled and without maintenance issues of checked exceptions, there is also a minor performance benefit (yes this is noticeable in some languages).

How do you know the try-blocks work since they are never supposed to be executed in a working program. You must test it! What are advantages of using exceptions over assertions and interrupt signals? Also if exceptions are never supposed to be used for control flow, then they are overused quite alot.

also exceptions generally (if not confined), encourage less experienced programmers to write shit message code, similar to gotos.

checked exceptions are really no different to maybes/eithers in terms of maintenance
T foo() throws E and Either foo() are the same function

you test the try catch blocks by throwing in mock object in your unit and component tests (your code is decoupled isn't it user?).
Yes they are overused, I agree with you, most programmers suck.

Literally the exact same as checked exceptions.

magical try catch, clear code, junior programmers not understanding, resource managment, finally etc, more keywords in the language..

Do you write unit tests for all your code? I only write unit tests for the most important code like hash tables, buggy code and code that is unlikely to be executed like a try-block. Without exceptions there is less code to test.

How old is old. Exceptions are great. GoLang's shitty error system is a pain in the ass. Who wants to return multiple values all the time just to propagate errors? Screw that shit.

Exceptions are so good, that they are even useful outside of error handling. In Common Lisp these are called conditions and they can get thrown for many reasons. Warning for example can be thrown and caught without stopping program execution. This means an inner library can issue warnings without using warning library or STD err

gigamonkeys.com/book/beyond-exception-handling-conditions-and-restarts.html

In both cases the error has to be handled, the only difference is the syntax used to do it. I agree that try/catch/finally bullshit is painful but checked exceptions mean you can't ignore it while unchecked exceptions allow you to.

by default I write code in a test driven way unless it causes problems dealing with legacy code or other programmers, I try to cover as much as I can with unit/component/other tests given time frames and whatever. you tend to find some weird shit in some languages with exceptions and marshalling across program boundaries... hmmm perhaps this part of why I went off them in the past... testing with exceptions shouldn't be too hard if your code is well broken down, but yeah it's more unnecessary stuff to learn.

>Exceptions are so good
Give me a single reason they are better than error codes.
>Who wants to return multiple values all the time to propagate errors
Perhaps you are propagating errors too much. Also it's just a single line of code most of the time unlike a try-block. That single line of code is not wasted since it declares to the reader the control flow of the error, unlike exceptions which are implicit.

>Everyone I talk to seem to hate them/find them useless

Attached: e55.png (800x800, 155K)

yeah kind of what I was getting at.. so i'd use runtime exception handling at a high level (for shit I didn't consider/logging in production) and types for program flow. this all depends on the app of course, some stuff cannot fall over or recover in production .. by default should try and think of everything that could go wrong and test for it.

It's a single line of code that must be repeated in every function. If the error is propagated through many functions, that's a line of boilerplate. Try/catch exceptions only require one additional block in one function.

>Give me a single reason they are better than error codes
>if (func1() == error1)
>return error1;
>else if (func2() == error2)
>return error2;

That's fine. Some things need more testing than others in my opinion. A game crashing is an annoyance, a pecemaker crashing is death.

not if you use a container type.

You mean an either/maybe?

> Error handling is done 1000 functions apart from the exception in the call stack in my code.
Your call stack might be too deep. It's common amongst oo programmer to write spaghetti code. I never have that problem.

>if_not_error()
>.then_do()
>.else_do()
>.unwrap()
I should guessed you are a rust fanboy

It's only unwieldy in C family shitlangs like Rust. In ML like languages like Haskell, it's extremely terse to manipulate error values.

Well, if you're interested in proving your code, the traditional way of doing it is with hoare logic, where each statement is of the form
{ precondition }expression{ postconditions }
and preconditions are in the form of first order logic assertions. You do a proof that the postconditions of one expression meet the preconditions of the next.

Exceptions kindof break this reasoning by skipping over the chain of proof.

nope, practically any modern language can do this.

>Rust
>C family

Yes, Rust uses C-like syntax rather than ML-like or Lisp-like syntax.

>It's unwieldly in Rust
?

Huh? With exceptions, you simply assume in the postcondition that the exception did not occur. Proving strong exception safety is also easy, since in that case, the postcondition is just the precondition. Proving weaker notions of exception safety is more complicated, but also less desirable. But that's only with Hoare logic, with type theory it's quite easy to reason about exceptions since the alternative "postconditions" are just the normal return type and the error type, where the overall return type is their sum.

>Proving strong exception safety is also easy, since in that case, the postcondition is just the precondition.
I mean that if an exception is thrown, you (re)fulfill the precondition, and if not, you fulfill the postcondition.

In Haskell you can chain maybe-failing functions trivially with do-notation. Or even just folding bind. In Rust it's all .()?.()?.()? noise.

Divide by zero, lack of permissions to a file, a timeout, running out of memory on the heap, your system entering an impossible state, etc.

do
y

Or you could do:
f x >>= g >>= h

Rust's way is not really much noisier.

Sure it is, there's four different tokens there rather than one identifier.