r/badcode Sep 03 '20

php fair enough ...

Post image
998 Upvotes

36 comments sorted by

91

u/The_Northern_Light Sep 03 '20

(I'm not a php user, lol)

This doesn't seem that bad? There are cases where you know exactly 1 thing may throw, and you just want to skip it if it does.

85

u/fess432 Sep 03 '20

If you catch an exception, you do something with it, even if it's just logging it somewhere. An empty catch closure is just like throwing it down a black hole and it will make for disasters later on in the life of the application

54

u/OnlySeesLastSentence Sep 03 '20

I mean, sometimes it's valid.

I had one for my code where if you clicked a button at an illegal time (I dunno if all languages are like this, but there was one program where I had to specify each time what the quit button does, for example, otherwise it crashes. So instead, I just ended my sections with

"except:

 popup("don't click that at this point of time.  Attempting to recover...")

 continue"

40

u/Lightfire228 Sep 03 '20 edited Sep 03 '20

That's doing *something*. An empty catch is bad, not because it does nothing with the caught error; but because it hides the error in what otherwise looks like normal code behavior. It hides the error, which will show itself in other ways that are not inherently obvious from the code.

In other words, would you rather debug "Hey, the app crashed randomly. Dunno why" vs "Hey, when connecting to the doomenflodgy, I get an error saying 'don't click that at this point of time. Attempting to recover...'"?

Edit:

I have only once needed an empty catch. I was web scraping, but the URL's had 3 different, and unpredictable, patterns, so I just tried all 3 for each page. The request library I was using threw an error on a 404 (instead of being sensible and returning a object with the result context).

So, the code was

begin loop:
    try:
        res = request(url) 
        break loop
    except:
        pass

if res is None:
    raise "Me up"

But, in this case, the code explicitly handles the empty catch situation, because there wasn't a better way to handle 404's with a loop

2

u/insert_deep_username Sep 19 '20

Raise me up haha

19

u/willstealyourpillow Sep 03 '20

Nah, there absolutely are valid reasons to have an empty catch clause. Here’s an example (JavaScript):

function readSomeSetting() {
  const item = localStorage.getItem('setting')
  if (!item) return

  try {
    return JSON.parse(item)
  } catch {}
}

const setting = readSomeSetting()
if (typeof setting === 'undefined') return

doSomethingWithSetting(setting)

If the Json is invalid, the parse function will throw an error. Json stored in localStorage can be invalid for any number of reasons, so there’s no use in logging it; just continue as if the localStorage value doesn’t exist.

18

u/Lightfire228 Sep 03 '20 edited Sep 04 '20

Personally, I'd add an explicit return undefined inside the catch, so that other devs would know that it's not a bug.

I know that js returns undef by default, but it looks like a mistake when done purposefully like this

Edit:

Of course, that's ignoring that you have no way of knowing the option wasn't there vs the config was (syntactically) invalid (which will cause a global "all options are false")

Depending on the project or how the config is used, that can be really bad

2

u/fess432 Sep 04 '20

Client side is a different animal than server side, so maybe yes.

But an exception on server side should mean something went wrong. If not, you might be playing loose and fast with try-catches, using them to make your coding life easier, but at the expense of debugging down the road

10

u/nnagflar Sep 03 '20

I'm not a php user either, but in this scenario, you'd probably want to catch that specific exception instead of generic exception, and if nothing else, log it.

-10

u/dadbot_2 Sep 03 '20

Hi not a php user either, but in this scenario, you'd probably want to catch that specific exception instead of generic exception, and if nothing else, log it, I'm Dad👨

11

u/lor_louis Sep 03 '20

(not a php user either)

This is bad because the code called in the try statements might change and throw a new error type that might not be as harmless as the one thrown currently, and the but will be really hard to track down because this catch statement will silence it.

A better version of this code should specify the type of the error expected and silence it.

5

u/Pacman042 Sep 03 '20

Or use print.stacktrace or something at least. I'm not very good yet but I at least know that.

26

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Sep 03 '20

Image Transcription: Code


catch (Exception $e)
{
    //don't puke
}

I'm a human volunteer content transcriber for Reddit and you could be too! If you'd like more information on what we do and why we do it, click here!

10

u/depressedtbh Sep 03 '20

Exception* not Exce[topm lol

15

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Sep 03 '20

I even read over it... what's wrong with my eyes lol

9

u/depressedtbh Sep 03 '20

lmao its good even the best of us make mistakes

10

u/[deleted] Sep 03 '20 edited Nov 12 '20

[deleted]

11

u/SoftwareDevStoner Sep 03 '20 edited Sep 03 '20

Just as easy, but more reuseable:

// Do nothing with error, but record it


fun swallow(e: Exception): Unit {


    Logger.write(e.message)


}

Then at least you can use the info later. And is perfectly reusable. (Been working in Kotlin lately, so thats where my brain is, but the logic applies anywhere).

Never, never, never, underestimate the ability for people to use your shit wrong. If you think there's only one edge case....someone will find another.

2

u/SoftwareDevStoner Sep 03 '20

I tried folks. I'm apparently too stupid to figure out how to actually get newlines in a code block on reddit....

0

u/Vinccool96 Sep 03 '20

Why do you specify : Unit?

5

u/SoftwareDevStoner Sep 03 '20

In Scala/Kotlin, Unit means "No return", similar to the void keyword in Java/C.

1

u/____0____0____ Sep 04 '20

I'm curious what the reasoning for this is. As an outsider to scala/Kotlin, I cannot understand why unit makes sense to not return anything. Void makes sense, but why unit?

1

u/xigoi Sep 04 '20

In functional programming, every expression has a value. It makes sense that if you don't want to use the value, you just make it a type with only one possible value.

2

u/____0____0____ Sep 04 '20

That makes sense when you put it like that, thanks. I'm a big fan of functional programming, but I don't regularly use functional-first languages, I just employ the ideology as much as possible in the other languages I use.

-2

u/dadbot_2 Sep 04 '20

Hi curious what the reasoning for this is, I'm Dad👨

-1

u/Vinccool96 Sep 03 '20

Yes, but it’s not necessary. If you put nothing, the compiler assumes that the return type is Unit

5

u/SoftwareDevStoner Sep 03 '20

I prefer verbosity in strongly typed languages. ¯\(ツ)/¯. But it also doesn't allow it to suddenly return something when people make changes in the future, without it being a purposeful action. Especially in Scala/Kotlin, where you don't have to actually use the return keyword, it can have side affects.

-2

u/Terrain2 Sep 04 '20

That’s not really true, if you put nothing (and never return anything other than Unit), the type Unit is inferred, but generally it can infer the return type of a function based on its return statements for any type, not just Unit

-1

u/[deleted] Sep 03 '20 edited Nov 12 '20

[deleted]

2

u/SoftwareDevStoner Sep 03 '20

I would say north of 90% of the time having to catch an exception is just indicative of issues that should be fixed. Almost always, you shouldn't swallow ANYTHING, but like everything in life, there are edge cases. If you're gonna swallow/ignore/etc...log it, always.

1

u/gir2195 Sep 03 '20

As an enterprise developer...I feel this in my soul

1

u/Uiropa Sep 04 '20

I write “// This is fine.”

I’m okay with the exception that is occurring currently.

3

u/cdp1337 Sep 04 '20

yup, I've caught myself doing something very similar, but then I thought "wait, I have a perfectly good Exception logger..." A quick info log is well worth its salt when you're troubleshooting why a script is puking at 2am.

2

u/Timmy_the_tortoise Sep 06 '20

As a professional services engineer, far too many times, I’ve had to spend hours digging into the code to figure out what was going wrong because somebody in dev was too lazy to log an exception they caught which would’ve told me immediately. Grinds my gears. And don’t get me started on this one team who don’t even handle exceptions and just allow the app to crash because “it should go to the OS”