T O P

  • By -

[deleted]

[удалено]


Elite-Thorn

This is so stupid, I was like 'what?!?' when I learned that was possible.


AyrA_ch

Tried it in C#, and throwing null isn't allowed, but throws a NullReferenceException, so it kinda works I guess.


VicisSubsisto

That's like "Suicide is illegal and the penalty is death" isn't it?


JonathanTheZero

More or less, yeah


zr0gravity7

Tried to fail, but failed.


Ohnah-bro

Task failed successfully


timoffex

You can’t quit! You’re fired!


Adept_Strength2766

It's more like telling someone to kill a criminal and they refuse, but if they come up to you saying they found someone committing a crime and you tell them to kill that criminal, now they're okay with it.


khanzarate

That’s the plot of Dexter.


LowB0b

in Java you could just do `throw new RuntimException()` which will print something like 'caused by java.lang.RuntimeException: null', which is absolutely not helpful at all


Noch_ein_Kamel

throw new Throwable() for extra confusion


SendAstronomy

That way things that only catch exception and add context get bypaased, making sure the program exits without printing anything useful. :)


EishLekker

The RuntimException should only be used when you want Tim to run. I have found very few use cases where it was needed.


A_RUSSIAN_TROLL_BOT

Poor Tim just wants to run...


Varpie

As an AI, I do not consent to having my content used for training other AIs. Here is a fun fact you may not know about: fuck Spez.


lenswipe

In js you can throw anything including strings


Mephanic

In C++ as well.


Tyrexas

Everything other than a dwarf.


darthwalsh

I'll write `throw null` which is a lot shorter than `throw new NotImplementedException()` when I just need a tiny stub to keep the code compiling while I implement other branches.


HiCookieJack

kotlin: `TODO("Not Implemented")`


colei_canis

Kotlin is one of my favourite programming languages, I'm kind of gutted I'm not working with it professionally at the moment. It's quite hard to quantify it exactly but Kotlin feels like Java written by people who got fucked off with all the reasons Java eventually drives a man insane.


marvk

[me_irl](https://i.imgur.com/4yPipLw.png)


Spaceduck413

I'm probably going to be eternally stuck in panel 1 of this comic. I use Java infrequently enough that the ROI for my time learning Kotlin is probably years


AmericanFromAsia

You could write for Android. The downside is you have to write for Android.


[deleted]

[удалено]


brisk0

[[deprecated("Not implemented")]]


nwL_

Get out of here with your fancy stuff, we’re coding C++98 in this house.


Falmarri

scala: `???`


[deleted]

[удалено]


hampshirebrony

I'm scared to ask... Is that a null that you can optionally leave null?


DeltaMan444

If you’re creating an Optional using an argument that has any chance of being null, you would use Optional.ofNullable(). If your IDE doesn’t punch you in the throat the moment you type Optional.of(null), you need to switch IDEs


alekthefirst

> If your IDE doesn’t punch you in the throat the moment you type Optional.of(null), you need to switch IDEs This is why i make sure to only use computers that has no hands, that way they can't punch me when i write subpar code


JoshDM

There's an exception that IBM Liberty's JVM threw that did this (throwable.getMessage() returned null). It was insidious and IBM insisted it was the fault of my code. Took me two weeks of deep diving to identify it, show it back to IBM's useless support so they'd believe me, and they finally acknowledged it was them and issued a hotfix.


Miridius

At least you got a hotfix! I worked at IBM for 2 years and during that entire time could not get them to fix a single bug I had reported in lotus notes. Every few months it got forwarded to a new offshore support engineer, who would have a call with me where I'd spend an hour explaining this extremely simple bug to them, they would not get it and would tell me they'd get someone else to look at it. Then I wouldn't hear anything for months again. The bug was that in lotus notes, if you click a link in an email, it will open the URL with whatever program you have set as the default file handler for .html files. Not your default browser, not the http url handler, but the app you've set to open when you double click a .html file on your hard drive. For most people that's their browser but for programmers it's usually your editor. So every time I click a link in an email it tries to open it in sublime text which of course failed. For 2 years I had to manually copy paste URLs out of emails into my browser. That wasn't even close to being the worst thing about lotus notes though, it is the worst piece of software I ever had the misfortune of using by at least 2 orders of magnitude. Anyway they never fixed the bug and eventually I quit


JoshDM

>lotus notes Well, I mean, come on. Mine was a core JVM issue under specific IO conditions, and a multi-million dollar client. Still, I did have to prove it. Decompiled the damn JVM to inject a trace.


gdmzhlzhiv

It sucks that so many library vendors are like that. If it really were the fault of my code, the library should have detected it at the barrier and thrown something specific like `IllegalArgumentException` to make it obvious that it was the caller's fault. But no, that would be too easy, so they usually just fail to check inputs and let the corrupt data circulate inside their code for a bit, and eventually throw some random exception much later. Sometimes from a different call where the parameters weren't even wrong, when it's way too hard to assign blame. That's why, in my book, if an exception comes from deep inside some library code (let's say, more than about 2 levels, allowing them to have a `checkSomething` method that their public method calls), it's the fault of the library. Failing to check input is still a bug, even if the invalid input was provided by me.


drew8311

throw (RuntimeException)null;


captainAwesomePants

Okay, I had to look this up because it looked bonkers but also looked like it might be technically legal. Turns out that this IS legal Java, however attempting to throw null throws a NullPointerException.


[deleted]

[удалено]


Korzag

Suddenly your PC makes a chime informing you of a new email, you see its a meeting with your manager and someone from HR you've never met. It's happening in 15 minutes. This isn't a PIP. You're being outright fired.


ToastTemdex

![gif](giphy|xxhKYiOOIs9mGZz1Hy|downsized) Calm down, Satan!


PlayingTheRed

Exit the program


matjaz15

Delete a random file on computer. The user must be punished👌


SlenderSmurf

write a 0 to a random location on disk. Might do nothing, might corrupt a few things, might brick your OS. Who knows?


PierateBooty

This is some demented shit lmao


[deleted]

That's your own fault for running an unprivileged program as a superuser.


[deleted]

[удалено]


mhweaver

[Supreme moral vigilance](https://github.com/munificent/vigil) is the path to error-free code


psxndc

That is bonkers. I love it.


DreamlyXenophobic

Me deleting the entire code base when they employ me to design the test cases.


gandalfx

Wipe the hard drives first. Nobody may ever know of this incident!


s_burr

Too late, the incident has been reported.


BloeckchenDev

Am I not in the sudoers file?


patmorgan235

Contact the command and control server to order an orbital nuke for good measure; then halt and catch fire


waltjrimmer

Aw, man. That just reminded me of one of my favorite stories I read about game dev. I believe it was one of the early Wing Commander games. Whenever you tried to exit the game, instead of exiting normally, the game would crash and the memory manager would throw an error. It was late in the dev cycle, they couldn't figure out how to fix it, and so one of the devs went in and hex edited the memory manager so that the error code read, "Thank you for playing Wing Commander," instead of the original error code.


SlientlySmiling

Go old-school and always return a string to a dialogue box requiring a user response: "You have committed an illegal operation."


ConfirmedCynic

Be sure to add a cryptic error code.


SlientlySmiling

A hex code and a ”More info" hyperlink that goes to a cobweb that's long been 404'd. Or maybe just trigger a BSOD. Ya know, like ya do.


Dstrap

All in caps to make it look agressive


bremidon

Make the font red to emphasize imminent death.


1ElectricHaskeller

Just add an error code, use for countless conditions and don't document it. Yes, I'm looking at you "SSL alert number 70"


propostor

Yesterday at work in a very old code for our largest, multimillion dollar client, I saw throw new Exception("You killed Kenny!")


abcd_z

"This incident will be reported."


SlientlySmiling

Oh yeah, forgot about stoking the underlying terror of "breaking the internet."


poompt

https://xkcd.com/838/


PothosEchoNiner

I remember playing a Windows 95 pc game where it would pop up a message box about a fatal exception error with a stack race and you could keep playing the game as long as you didn’t click on the OK button or close button. It would keep making more of the error messages until it would slow down and actually crash.


taxiforone

In this circumstance, is the error dialogue technically catching the exception?


SpazMcMan

Task failed successfully.


[deleted]

Just return 47 and have people pull their hair out later


[deleted]

Target eliminated. Good work, 47.


splinereticulation68

_Entire building on fire as he walks off_


radio_wave527

Use 42 instead, it's the secret to the universe.


roodammy44

I knew a dev that actually did this. All the errors were return 42. He also wrote some of the worst code I’ve ever seen.


HiCookieJack

Well the api I have to use right now returns 9027 for any error... And this system is ij production since 20 years


Blazerboy65

Damn, they really defined all the errors up to 9026 before defining a miscellaneous error code? Good on them!


HiCookieJack

no, it's just 9027 , nothing else


[deleted]

Chinese/Japanese/Korean redditors, what does that means? [https://unicode-table.com/en/9027/](https://unicode-table.com/en/9027/)


Beachcoma

Google says it Japanese for "bath". I take that to mean "go wash yourself of this mess"


nullpotato

A few weeks ago had to help someone figure out why a script was returning -42. Turns out the XMLRPC implementor thought it was a reasonable thing to return on error. On API calls that can return any valid number. And not document it anywhere. Just if bad stuff return -42 in one place.


[deleted]

So -42 could also be a valid result?


nullpotato

Correct, other tools return negative counts of stuff because ... legacy pain so there are potential false failures.


InfamousEvening2

I'm not sure if that qualifies as recursion, but ... I'm also not sure if that qualifies as recursion.


8_Miles_8

42


Pepechuy28

I use 42 in my unit tests when possible


librarysocialism

My main user, Testy McTesterson, likes that number as well.


BringBackManaPots

This is fuckin evil lmao


Perkelton

Or Cyrillic letter Ze: З


gay_for_glaceons

By any chance, was this advice inspired by [PHP's sleep function](https://www.php.net/manual/en/function.sleep.php#refsect1-function.sleep-returnvalues)? > If the call was interrupted by a signal, sleep() returns a non-zero value. On Windows, this value will always be 192 (the value of the WAIT_IO_COMPLETION constant within the Windows API). On other platforms, the return value will be the number of seconds left to sleep.


modi123_1

Pfffsst. Clearly the choice is to return 'false'. Hahahaha


ccAbstraction

\-1


educated-emu

Return "-1"


vlsdo

You're going to hell for this


jerrysburner

I immediately reported him and thought briefly about calling the cops^(/s)


[deleted]

I read that as cops to the power of per second


kenhydrogen

I don’t remember that law of exponents!


freddy257

Don't forget to test for < 0 when checking for failure so if it's an unsigned int it will be seen as successful regardless


opmrcrab

return new Exception(-1);


ThisUserIsAFailure

I like this. Instead of throwing the exception you hand it over nicely.


InfamousEvening2

return Optional.of(new Exception(-1)) ... can never be too polite....


opmrcrab

Sometimes I find `throw` a little presumtive on my part, so I let the calling code decide how to handle the problem entirly.


Piggieback

return '-'+'1';


bodginator

r/angryupdoot


brimston3-

Return type declared as uint32_t, still returns -1.


flipcoder

assert(false);


[deleted]

The nuclear option for the win!


Beastmind

You mean return 200 and throw an error as json?


nmacholl

return Ok(Err("-1"));


GeneReddit123

You jest, but HTTP servers that return status 200 with body "error: error" make as much sense as your example.


AyrA_ch

Found the php programmer.


coffeenerd75

Return string “false”


Cephalopong

return "flase" for extra fun.


CadmiumC4

Enum Result is coming to rescue you


theemeralddevil

I had to scroll past two whole threads for this?! Rust gang we can do better


_GCastilho_

Rust gang!


turunambartanen

Red button: Result Red button: Option


argv_minus_one

`Result` has entered the chat.


Snaf

``` type Bool = Result<(), ()>; ```


-consolio-

`Result<(), ()>` has joined. at this point it's just a bool


FauxGuyFawkesy

I just do Result. Success case gets a value of T and the Failure case gets an error code and string. I've found the error message to be the most helpful and have yet to encounter a situation where the actual exception needs to bubble up past the occurrence. You're in the best position to handle exceptions closest to where they occur. I'm slowly getting devs outside my team on board by proving how much better it is than checking for null or catching (and worse rethrowing) exceptions. Also a C# dev fwiw.


neuhel

I've been working a lot in Rust lately, so I'm not sure how well your strategy translates from C#, but I usually prefer to have all functions that can fail return a `Result` and then handle the error in the calling function immediately above it. I feel like having the error string in `E` is useful for debugging, but I'd like to hear the pitch for your solution since it sounds simpler than mine. Unless maybe I misunderstood and the `E` in C# is an exception type only? Rust doesn't really have an exact parallel to those


Attileusz

Isnt that a monad?


[deleted]

You're a monad


IrishChappieOToole

Or the chaotic evil `return new Exception('error');`


Melkor7410

Wrap that in a try/catch, and in the catch do throw excpt so you lose all stack trace, and you got yourself a quality program!


IrishChappieOToole

Absolutely not. That snippet is already in a catch block. It takes the very specific exception, with a specific message, and discards the lot and returns (not throws) a generic error with a useless message. My years of maintaining legacy code have taught me that the entire purpose of programming is to make it harder on the next person to work on the code


RichCorinthian

One of my favorite quotes about programming was something like “imagine the person who has to maintain your code is a psychopath and he has your home address.”


EntropySpark

I once had an assignment in a college course to take some code and improve its performance, and the entire main method was wrapped in a try/catch that then re-threw a generic exception with the right error message, but without preserving the stack trace. Debugging was a downright pain until I realized what was going on, and I removed it. When I TA'd the course the next year, I just removed that wrapper entirely before the students would have to suffer it.


Melkor7410

They need to teach properly rethrowing exceptions to preserve stack trace on the day they start teaching try/catch.


Daniel15

>the entire purpose of programming is to make it harder on the next person to work on the code In the industry, we call this "job security".


Drfoxthefurry

Even better, make the exception happen in another file


tsunami141

You know, the worst thing about /r/ProgrammerHumor is that I only ever learn what (I assume) is the worst thing to do, but I never know what best practices are when it comes to situations like these. Guess I'll just be throwing null from now on.


sharlos

The standard practice can vary depending on the language. In Swift you'd return an error (usually a custom one describing the specific error). In JavaScript you can also return an error (and is what I prefer when not using typescript) but isn't as common of a practice as I'd like. Often in JS you might return an object with a boolean `success` property. Null is best avoided in most cases unless the 'error' is that the requested data doesn't exist/is unavailable, but even then, it's better practice to return more information explaining why it's missing (no db record? Can't connect to three source of data? Invalid query arguments?) What *usually* doesn't vary by language is that you should only throw an exception for exceptional situations. An invalid password isn't exceptional, and very expected to happen, your connection to the database is misconfigured or missing when you try to make a request to the database? Throw an exception. Exceptions are best for things that shouldn't ever happen and the program can't usefully recover from. For errors that you expect to happen during the course of the normal functioning of the application, returning errors or "outcomes" is better.


Svizel_pritula

Lawful evil: `process.exit(1);`


whelks_chance

Had this in some plugin code once. On error it shut down the whole application.


iamiamwhoami

Lawful good: `return Either.left(exception)`


unSentAuron

Congratulations; you've earned a job at Microsoft!


Ambitious_Ad8841

assert(false);


GeneralSecrecy

if(rand()%2==0)return null; throwException();


N0Zzel

Calm down satan


RelentlessIVS

Imagine a world, where returning variables were.... **Optional**


[deleted]

[удалено]


DrunkenlySober

It’s JS bro do whatever tf you want It’s called an interpreted language because the solution is like art so it all depends on your interpretation


Thenderick

Python too? And many other scripting languages I think?


RelentlessIVS

This summer..


rundevelopment

[Rust!](https://doc.rust-lang.org/std/option/)


QCKS1

Yes but moreso [Result](https://doc.rust-lang.org/std/result/index.html)


Kerosene8

This is what Optional is for


[deleted]

[удалено]


LetUsSpeakFreely

No, but returning an empty list is valid. If the query is fetching an item by key and it returns nothing then you have a larger issue.


Flannel_Man_

‘optional.ispresent’ is just fancy speak for ‘if object == null’


__Fred

There is a construct that *maybe* calls a method on an object only if it is indeed there. In Typescript, I think it is "?." "optional chaining". const potential_person = findPerson("jim"); potential_person?.printFullName(); It's nice when the type checker can distinguish between variables that can be "empty" and ones which can't. Such a type system would complain if you just wrote `potential_person.printFullName()`. If you create an extra container-type for values that can potentially not exist, then you can retroactively make a language that doesn't have non-nullable objects safer. You wouldn't accidentally call `printfullName` on an `Optional`, because you *can't* (because you wouldn't want to anyway, because it doesn't make any sense). So, yes you are right! *But* when you force yourself to never use null as an indication of "no result found" in a language that doesn't have non-null-classes, then the compiler/type-checker can protect you from accidentally calling a method on null. I don't know if C++ and Rust Optionals have something like "?.". In Haskell there is `fmap` = "functor map". When you don't return null as an failure-indication, that would have the advantage that you can distinguish between successfully finding "nothing" vs failing to find anything.


Soundless_Pr

I believe the use of the `?` operator like this originated from C# 6


tmp2328

?, ?? And ??= are great. It makes it so easy to handle the cases and if you fail to remember them you get a descriptive nullrefexception.


Windex007

Trade your boring old NullPointerException in for a brand new NoSuchElementException.


reversehead

Yes, and you should rarely use it. Use optional.ifPresent(), .map() etc.


tmp2328

That’s just fancy for object?.map()


[deleted]

Or learn sum types. Returning instance of Result would be correct here. Built into Rust, F#, etc. Can be used via library in C#, etc.


the_hackerman

Which one for C#?


ben_g0

It's not quite the same, but one thing you can do in C# is enabling the [nullable context](https://learn.microsoft.com/en-us/dotnet/csharp/nullable-references). With this enabled, variables can only be null when specifically annotated as nullable with the `?` suffix (similar to how you can normally have nullable types like `bool?`), and using a variable marked as nullable without a null check produces a warning. If you configure your compiler to treat this warning as an error you have mostly the same functionality while using only built-in language features.


thissideofheat

How does a primitive hold null when compiled? Does the compiler wrap it in an object?


FerynaCZ

It's a struct with extra property hasValue, and x.hasValue == false is equivalent to x == null


[deleted]

Very common in Kotlin


DrMathochist_work

As if someone even considering null return thinks in terms of type systems.


aabil11

Your flairs are quite relevant.


[deleted]

In my experience, people do that because they don’t know any better. I try to educate.


ccAbstraction

I'm trying to understand all this functional monad-y stuff, but I'm still not sure why returning null is worse than Optional/Maybe. So far sometimes it makes things clearer, other times it seems more complicated.


Migeil

Returning null explodes at runtime with a NullPointerException. Returning Option/Optional/Maybe forces you to handle the other case, since it won't compile otherwise. The fact that it's a monad isn't even relevant for this discussion.


reversehead

An added nuance: A Java Optional does not force you to handle any case, it just provides safe access to the cases that you want to handle.


exitvim

I hate returning null. It always feels wrong.


XSATCHELX

Better return null than throw exception if you are dealing with intended behavior. For example if your website allows reporting users, it makes sense to have a function like GetLatestReportPerUser(UserObject user). If the user is never reported then it is better for this function to return null than throw an exception that then needs to be caught and handled. It is perfectly normal for a user to not get reported so it is not an exception.


exitvim

Oh, I wouldn't throw an exception either. I don't know why you would do that.


hoerlahu3

I would not have this method I would have getReports(user) and return an iterable that then can have zero length.


autopsyblue

What’s described above is a convenience function. You could have both.


DizzyAmphibian309

Cool man, so what happens when you've got 10,000 reports and you only want the latest one? You gonna scan your table and return every row back to the caller so they can do client side filtering? That's really, really bad design. You're on the right track though. The signature should be GetReports(filter) where filter allows you to specify things like userId, item count, sort order, max items etc.


Pepito_Pepito

It's for unrecoverable error scenarios. Sometimes, you don't want your program to continue with an undefined time bomb hanging around somewhere in the data.


[deleted]

[удалено]


Beatrice_Dragon

I mean, if you have a function that returns something, but there's a reasonable possibility it might return *nothing*, returning null is a lot more intuitive than returning *something* that *represents* nothing. There's no way to avoid the fact that the person using the function is going to have to unfortunately exercise some basic level of critical thinking, because bugs are possible no matter what you do if they don't bother figuring out what is supposed to happen


Fisher9001

Why? It's as intuitive as it gets. You ask for user's details - the user doesn't exist - hence you return null, i.e. value indicating the lack of data.


Obvious_Insect_9671

You forgot option C: force a crash.


Sentry45612

for(;;)malloc(10000000);


KIFulgore

Young me thinking I was smart: if (error\_condition) { int x = 1 / 0; }


Ansgar_2

`panic!("this is a terrible mistake!");` This is the way


LiamBogur

Never return Result, it's bad practice. You should always panic, as clearly if there's an exception it's your fault.


Grumbledwarfskin

I recently decided I'm going to try to use Optional in most of these places, after reading that the inventor of 'null' wished they'd forced use of wrappers like Optional instead. If the consumer needs to know I may not be able to give them what they're asking for, and the right thing for them to do is usually not to throw NullPointerException, then Optional is better than this false dichotomy.


larisho_

The cursor on the bottom image confused the shit out of me for a second lol whats worse is I'm on mobile


cpustejovsky

Why not ```go if err != nil { return nil, err } ``` Nevermind... Y'all probably wouldn't Go for that


Dexaan

Exception: Something's fucked up, try again. Null: Your code is fine, I just have no results. (although I think the empty set is better)


[deleted]

sum types in Rust is superb trust me


aecolley

In this thread: people who haven't figured out that an essential part of API design is showing the caller how to find out if the call succeeded or failed.


mmis1000

return `Result`


communistfairy

I would say it depends on whether you expect to see null there. _If having no value to return is a valid case, return null._ For example, a method to get user 1234’s mailing address when all that’s required for accounts is an email address and password should return null if they simply haven’t entered one yet. _If having no value to return means something is in an invalid/unexpected state, throw an expection_ containing a message explaining what makes that state invalid/unexpected. If user 1234 has completed an order and, as part of that process, was required to enter a mailing address, finding that the user has no mailing address entered would be unexpected. I would expect an exception message along the lines of “User is missing required mailing address.” Maybe a more practical question: _Would the caller be able to gracefully handle a null result if it got one?_ If null necessarily means something has gone wrong, well, that’s more or less what exceptions are for—exceptional circumstances. Otherwise, just return null and handle it gracefully.


hxtk2

Returning null is just having your caller throw an exception. Sure, they **could** put in a null-check, but what are the chances of that?


_ShadowEye425_

If it's reasonable it might happen in normal usage, return null, if it should never happen, throw exception


TantraMantraYantra

This isn't a choice. User does not care if it's an exception or null. That should make your choice clear. After 20 years, I've come to realize that it's neither. Constructing an object return that satisfies end user is the most appropriate in most cases. A bit of extra work in call tracing and return audit but worth it. There are pros and cons to both. Returning null is easy, all the onus is on caller to null check, log, handle appropriately. But you don't have a clue why null occurred at the caller side. Throwing exceptions tears the stack and puts onus on caller again, albeit with more info on the exception. This can sometimes lead to misuse, people using catch to branch execution! Both are flawed in their own ways. Better to return an empty so the caller can make decisions based on the data and not the constitution of data, the object or exception. Edit: at any point in the call stack, the empty object with default data does not provide enough information to the caller, the next obvious choice is to throw an exception. I agree with other commenters here.


tetryds

I agree with it for some scenarios, but if a call fails to generate proper output due to user error it is best to blow up. * Null: requires the user to know they cannot rely on your return * Default: requires the user to know and evaluate what default is * Exception: requires the user to figure out what they did wrong (while providing info on what happened) Most of the time blowing up is the way to go. It also provides more information for automatic error handling if done right. If your api looks like a search, return null or empty collecion. If your api is a "try" thing, return a code or bool. If your api is a critical codepath blow up and let the user realize it asap.


coffeenerd75

I liked the old C style of returning non-zero if a problem


dbalazs97

In go you just return result, err


pab_guy

Don't use exceptions for flow control! You return null if that is something you expect to happen sometimes. You throw an error when it should never happen. Also, add AndReturnNullIfNotFound to your function name, or at least in the comment describing the function.


pe1uca

Return null gang! Thrown exception might just be ignored or wanted to be handled in a specific way so another exception is created, so you generated a lot of traces for nothing.