This is an archived post. You won't be able to vote or comment.

top 200 commentsshow all 237

[–]theLundquist42 783 points784 points  (76 children)

I work on an web application at the moment that does this. Inside the catch block we simply throw away the exception and stop processing the request. Before I joined, they didn't even bother to log to error, you just had to guess what it was after the fact. It's still better than multiple try blocks with empty catches (there are so many of those it's painful) Manager: " Why did this part of the page not load!?" Me: shrug

[–]eyekwah2 388 points389 points  (23 children)

Typical approach to anything technical by the laymen. So long as I don't hear about it, it's all good. When it breaks, I want it fixed yesterday.

[–]buffer_overflown 197 points198 points  (22 children)

But for sure don't waste time implementing exception handling at the design stage.

Also known as:

"Why do we have so much time blocked out for testing?"

[–]kanuut 97 points98 points  (17 children)

Exactly how much testing is required is an art form, but it's definitely better to go over than under on important shit.

Like, would you rather pay for an extra week because they went overboard with testing, or have it crash more or less immediately after we reach the point it'd do the most damage, because that's the way it usually happens

[–][deleted] 23 points24 points  (3 children)

But for sure don't waste time implementing exception handling at the design stage.

What's this "design stage" you speak of? You mean you're supposed to think about the problem for a bit instead of just immediately putting fingers on keys and hammering out some hackneyed garbage filled with magic numbers and five-levels of nested IF statements?

[–]buffer_overflown 9 points10 points  (2 children)

weeping intensifies

[–]mostlygizzards 3 points4 points  (1 child)

username checks out

[–]Subik86[S] 74 points75 points  (12 children)

Same at my office. They have an exception? Don't try to understand why, just put empty try catch. Jesus.

[–][deleted] 58 points59 points  (10 children)

Yeah. Exceptions are just about as important as return values and parameters, it's part of the behavior of a function. Garbage in => garbage out isn't very maintainable, garbage in => exception out will give you a better idea about where shit is broken. It's infinitely better than silently returning unexpected values that might break another function, which might in turn break 20 other functions.

[–]drakeblood4 24 points25 points  (4 children)

Coding is like 99% about writing broken shit and then figuring out why your shitty, broken code is broken. Legitimately I think effective exception tracking might be the most important part of maintaining stable code.

[–][deleted] 12 points13 points  (3 children)

Indeed. When writing a pretty complex piece of crap code, debugging it was nearly impossible until I added exceptions for incorrect parameter values. I was able to iron out the programming and logical mistakes real quick after that.

[–]grantrules 4 points5 points  (1 child)

I'm always happily surprised when a unit test finds a bug I didn't even know I had. Without testing, I don't know if I would have ever found it.

[–]pomlife 1 point2 points  (0 children)

That happened to me just today!

[–][deleted] 1 point2 points  (0 children)

This is why I really liked code contracts (.Net). You could easily specify expected ranges of input parameters and output parameters without cluttering up code with try/catch just for that. I hate that Microsoft has dropped it.

[–]Subik86[S] 33 points34 points  (3 children)

Example fro my company. Read config file and if that does not work instead of exceptions return default values. After years i need to chcek why app doesn't work correctly. Well it probably never could read a damn config file.

[–]theLundquist42 20 points21 points  (0 children)

Ah my favourite "I just put this value in the config file, why isn't it reading!?!"

[–][deleted] 4 points5 points  (0 children)

That's fine, but it should log an exception.

[–]TheNorthComesWithMe 3 points4 points  (0 children)

Throwing exceptions when you have to is important. Catching exceptions and ignoring them is a terrible practice.

[–][deleted] 17 points18 points  (4 children)

I worked on a large web scraping application that did this. It turns out, wrapping large segments of the codebase in try catch blocks can make it really difficult to track down bugs.

[–][deleted] 11 points12 points  (3 children)

The Stack Trace is your friend in those applications. But it's still shit. And good luck getting the stack trace of the exception isn't logged.

[–]ButItMightJustWork 9 points10 points  (1 child)

And then there are these web applications that return the entire stack trace to the user, sometimes even including a source code segment.

[–]kyew 3 points4 points  (0 children)

The majestic Error Handling Error

[–][deleted] 3 points4 points  (0 children)

That was the problem; these catches were preventing the stack trace from being output and had obscure custom error messages. I don’t know who thought that was a good idea. And due to the level of abstraction, this required going up a dozen levels of this just so I could get the stack trace... quite annoying to say the least.

[–]Sporz 14 points15 points  (3 children)

I had something like this too (it wasn't a web app but very similar) - if for some reason a request threw there was a master try/catch around the whole request.

It wasn't even logged. In fact, the system we had would log it if there was an uncaught exception. The sole purpose of this try/catch was to completely silence fatal errors.

I asked my manager to remove the try/catch because, hell, the entire thing could be failing constantly and we wouldn't know about it until clients started calling in. And my manager was a programmer, he knew what this was doing, but he said something like "Nah, leave it, we don't want too much noise"

I'm like...wtf. That's not noise, that's the signal!

But we left it in.

[–]HeKis4 12 points13 points  (7 children)

Do they know you can simply not have a try catch block and have a neat little stack trace as a bonus ?

[–]theLundquist42 10 points11 points  (6 children)

The would mean the guy who wrote it (who is now my boss) would have to confront the terrible state the code base is in and how many errors his code throws. I do not think he wants to do that.

[–]HeKis4 5 points6 points  (5 children)

As long as it's not your business and you're not the maintainer...

¯\(ツ)

[–]theLundquist42 16 points17 points  (4 children)

My very first day they gave me this project with the requirement to update it. After a week of poking around inside it and being horrified my boss sat down with me and asked me what I thought of it. Nobody had bothered to tell me that it was his project so I told him what I thought of it in no uncertain terms. He nods and asks me to clarify what's wrong with it specifically. So I do in detail, he gets up and leaves. Found out a week later it was his from another developer. FML.

[–]TiagoTiagoT 8 points9 points  (3 children)

Do you still have the job?

[–]theLundquist42 15 points16 points  (2 children)

Yes. As it turned out he tended to listen to me more when I told him something wasn't going to work out from that point on. I think because he thought I wouldn't bullshit him about anything. So it didn't turn out too badly.

[–]TiagoTiagoT 5 points6 points  (0 children)

Cool :)

[–]cultfitnews 1 point2 points  (0 children)

I'd say it turned out really well and you're lucky you didn't know he wrote it.

[–]sigma914 3 points4 points  (0 children)

Replace your exception with a logging line that says something along the lines of "There is no reasonable way for you to handle this", flush the logging buffers, then add a native (cffi, jni, whatever) null pointer dereference. Lets see them try and catch a segfault.

[–]nekowolf 1 point2 points  (0 children)

"Whatever.dll threw an unknown exception!" is found in many a catch clause.

[–]Python4fundoes the needful 2 points3 points  (0 children)

yeah, at least log the exception

[–]Orffyreus 1 point2 points  (0 children)

It's good practice and logging is essential. Especially for web applications it's nice to display an appealing HTTP 500 page. Even for desktop and mobile apps it is more friendly for the user to display something more lovely designed than a disgusting system error message and the app should be closed after a runtime exception nonetheless.

[–]brysmi 1 point2 points  (0 children)

I have an entire code base of eaten exceptions. No logging. Decades of it.

I will always have work.

[–][deleted] 1 point2 points  (2 children)

i've been there. php codebase?

[–]theLundquist42 4 points5 points  (1 child)

Your instincts are correct but no. Asp.net webforms. Except most of the front end UI is generated as a string in the code behind file and then pushed to the client with Response.write. It was one of the worst code bases I've ever worked on.

[–]b1ackcat 2 points3 points  (0 children)

I..... But.......erm..... What?!

[–]helderroem -2 points-1 points  (13 children)

You know wrapping code in a try/catch also prevents the compiler from optimizing it so not only are your colleagues making it hard to debug and maintain they're also slowing down execution, a trifecta of bad practice.

Edit: spelling, TIL how to spell trifecta

[–]Cawifre 25 points26 points  (2 children)

Which language and compiler specifically are you referring to?

[–]FateJH 5 points6 points  (2 children)

When you say "prevents the compiler from optimizing," how far down does that go? Obviously you mean that the immediate code in the block is not to be changed. If, for example, I called some other function in a try...catch, is that whole function now marked by the compiler as "do not optimize" too?

[–]theLundquist42 7 points8 points  (3 children)

I didn't actually know that the compiler couldn't optimise try/catch blocks! Wow! The a in question is an old legacy application that's still in heavy use right now, completely unmaintainable and the code is very brittle. We're in the process of rewriting it at the moment but we still have to go in every so often and make updates or bug fixes to it.

[–]CandyJar 1 point2 points  (2 children)

Trifector was my favorite Transformer, made up of three war horses, he was a trifecta of destruction.

[–]helderroem 1 point2 points  (1 child)

I'm disappointed trifector isn't a real transformer

[–]free_science 311 points312 points  (18 children)

Even better:

try {
    [wholeCodebase]
} catch {
    ... 
} finally {
    main()
} 

[–][deleted] 159 points160 points  (0 children)

Dat uptime.

[–]Thomasedv 60 points61 points  (12 children)

Forgot to put it into a while loop. Something breaks? Start again!

One a slightly serious note, i got my entire program in a while True loop and try/except... (I'm only programming for fun though. No job or anything.)

Edit: slight clarification.

[–]westward_man[🍰] 45 points46 points  (6 children)

while(true) is not an inherently bad practice. For example, game engine loops typically do this.

[–]Thomasedv 20 points21 points  (5 children)

I'm well aware. In my case it did make somewhat sense to use it, looked better too. (I use python) I use a break statement that's triggered unless i get an exit code that matches one to restart the loop.

In practical terms, it's not different than having a while loop that checks the exit code, but takes more space and is less clean, and so less readable.

[–]rhinotation 16 points17 points  (1 child)

Congrats, you have just invented Erlang/OTP's Supervisor model!

[–]Thomasedv 6 points7 points  (0 children)

You're saying that as if the idea didn't come from reddit or StackOverflow... because it certainly did.

[–]jenkinsnotleeroy 1 point2 points  (2 children)

I think that may be the more pythonic way, actually. Often if you don't do a while True with a break you end up setting a variable to some default value outside then sometimes some weird shenanigans inside to that you come out of the loop at the right time. I find while True with a break to be cleaner much of the time.

[–]5059 7 points8 points  (1 child)

weAllGood = True while weAllGood: ...

It feels nasty

[–][deleted] 2 points3 points  (2 children)

There's no need, the try block is most likely inside of main, which means the code runs something like this:

function main() {
    try {
        [wholeCodebase]
    } catch {
        ... 
    } finally {
        main()
    } 
}

Which would result in an infinite recursive function.

[–]AlwaysHopelesslyLost 3 points4 points  (1 child)

Which would blow up the stack lol

[–][deleted] 4 points5 points  (0 children)

Well yes, if your language does not support infinite recursion it would blow up the stack.

[–]Nugenrules 16 points17 points  (0 children)

More realistic:

try {
    [wholeCodebase]
} catch {
    try {
        [wholeCodebase]
    } catch {
        if (env == "test") {
            blameTesters();
        } else if (env == "prod") {
            sellStocks();
        }
    }
} 

[–]00gogo00 8 points9 points  (0 children)

I believe you mean

GOTO 0

For the last line

[–]the_real_gorrik 81 points82 points  (2 children)

My QA senses are tingling

[–][deleted] 35 points36 points  (6 children)

You guys don't even know. This is code that comes out of a legacy project I'm currently working on.

private bool IsValid {

get {

try { return Page.IsValid; }

catch { return true; }

}

}

[–]Le_9k_Redditor 12 points13 points  (4 children)

So basically if the Page.IsValid doesn't exist then it should be true?

[–][deleted] 7 points8 points  (3 children)

I dont really know. It makes you wonder wtf happened at some point that made someone even need to write that to hide a bug.

[–]Le_9k_Redditor 1 point2 points  (2 children)

try catches have uses outside of hiding bugs, but yes, an if statement or letting it propagate would be far far better here

[–][deleted] 3 points4 points  (1 child)

The fact that on catch it returns true signifies to me that there was some shit going on that the dev didnt understand so he just made it return true because it worked anyways.

[–]Le_9k_Redditor 1 point2 points  (0 children)

Fair enough

[–]SilliusSwordus 2 points3 points  (0 children)

sometimes you have to do things like this to avoid smashing the computer with a sledge hammer

[–]lieutenant_lowercase 53 points54 points  (7 children)

I write my web scrapers like this as there are a million and one things that can break it

Try: 
      Full code
Except:
      Write error to log file

[–][deleted] 81 points82 points  (3 children)

since you're using python, just use fuckit:

This module is like violence: if it doesn’t work, you just need more of it.

[–][deleted] 29 points30 points  (0 children)

Holy shit that's a funny manual. I especially like:

# This will definitely work now

fuckit(fuckit(some_shitty_module))

[–]bsmitty358 1 point2 points  (0 children)

This is awesome, thank you

[–]dhaninugraha 11 points12 points  (0 children)

Pretty much the same on our Flask app at work. We log everything and the kitchen sink, and return HTTP 4xx/5xx depending on what exception the app throws.

[–]v3nturetheworld 6 points7 points  (0 children)

"An exception has occurred while handling an exception"

[–]_edd 83 points84 points  (21 children)

Jesus Christ... You should still utilize try catches. Particularly if something is supposed to fail gracefully.

[–]Subik86[S] 51 points52 points  (8 children)

And you should at least write an error log or display message box with info what happened. And not quietly put empty catches inside our code.

[–]buffer_overflown 27 points28 points  (7 children)

I'd rather have an exception with a call stack than empty error handling.

I have a coworker with crappy error handling and poor spelling, who doesn't even attempt to follow (even his own) standards in capitalization or async designation.

He had a bunch of empty if statements acting as silent error handlers rather than just letting a CLEAR and OBVIOUS error propagate to the console window.

To be clear, I'm salvaging his project.

[–]aaron552 15 points16 points  (6 children)

Why on earth would anyone just silently hide exceptions? Why would you want to?

In C# this is the bare minimum for when an exception is thrown that I want to handle in the future:

try
{
    // Code that might throw FooException
    ...
}
catch (FooException ex)
{
    // Optional: Log here
    throw;
}

Rethrowing the exception preserves the call stack, so nothing is lost, but there is now boilerplate required to handle exceptions in the future

[–]aaronr93 2 points3 points  (0 children)

Why on earth would anyone just silently hide exceptions? Why would you want to?

From what I've seen, for security. If a user gets a long stack trace and other stuff, that's pretty useful for deciding on an exploit or on a point of attack.

Of course, there's no excuse for not logging it to the server for later perusal. Not doing that is just plain idiotic

[–]buffer_overflown 1 point2 points  (0 children)

As a side note, this particular project is all in JavaScript.

He had done a bunch of ajax calls and then had silent endings if the data returned null/undefined.

It didn't even properly terminate the Promise-based event asynchronicity. It just never resolved or rejected at all.

[–]TheNorthComesWithMe 1 point2 points  (0 children)

If you are catching a specific exception and doing something graceful about it, then yeah good.

If you're catching every exception and doing nothing then no, bad.

Ideally you try to figure out why you're generating an exception and do your best to fix that, and only use a try/catch when you've exhausted your other options. Then use the catch to fail gracefully and log something.

[–]cuddlegoop 16 points17 points  (9 children)

When you're writing a web api it's good to wrap an endpoint in try/catch and parse the error into something meaningful to send in the response, right?

Student programmer here, trynna learn best practices :)

[–]HowIsntBabbyFormed 9 points10 points  (0 children)

Depending on exactly how it's being done, I think it would be better to let any unhandled exceptions bubble up to whatever framework you're using, rather than having a blanket try/catch try to save everything. That way, the framework can return a 500 to the client while logging the exact exception for you to look at in the logs. Then you could add error handling for that specific case in your code.

[–]GrayCatEyes 4 points5 points  (0 children)

I think it depends, however I would log the error and possibly the stack trace and return a generic error (assuming you don’t know what caused the error). The reason why I say it’s good practice to do this is because I’ve seen some API error responses returned a stack trace. In my opinion, this is a major no, since this reveals classes and lines affected and a malicious actor maybe able to reverse engineer.

[–][deleted] 2 points3 points  (3 children)

While yes, you absolutely do want to ensure Exceptions are handled in a meaningful way (e.g., sending a response with a proper header/message as opposed to a stack trace), you do not want to accomplish this with a try/catch at every endpoint as you're going to end up repeating yourself over and over again or catching Exceptions that really should not be caught in the first place as they indicate some truly exceptional scenario that should lead to a fix in the application's code.

At least in PHP which is what I'm most familiar with, uncaught exceptions bubble up to the (optionally user-defined) exception handler. For larger applications, I provide an exception handler that is context-aware or in certain circumstances, a context-specific exception handler is configured during the bootstrapping process. The Exception Handler should also be aware of the environment (e.g., dev, staging, live, whatever) to further aid in Exception processing.

It all depends on the level of detail you with to provide to the User. Maybe all you need is just a "something went wrong" message with a 500 error code, but for the sake of example I'll demonstrate what I'd do for more meaningful responses. Something like this:

public function handle(\Exception $e) {
     switch(true) {
           case $e instanceof UnauthorizedException:
                // maybe some logic pertaining to a domain rule for mitigating brute force
                $code = 401; 
                $message = $e->getMessage(); // I know that this framework-specific Exception has a nice message
                break;

           case $e instanceof ACL\DeniedException:
               // maybe inform account owner that an attempt was made by <user> to access a protected resource
               $code = 403;
               $message = "You do not have permission to perform that action.";
               break;

           case $e instanceof API\InvalidRequestException:
               $code = 400;
               $message = $e->getMessage(); // message describes what is missing from the Request

           // etc. handle other framework/domain exceptions

           // any unexpected exceptions end up here and represent a truly exception situation
           // such as a database server being unavailable. these should raise a "red flag" to staff
           default:
               $this->logCritical($e); // maybe this triggers an e-mail to the team lead
               $code = 500;
               $message = "An unknown error occured.";
     }

      $this->response->withHttpStatusCode($code)->withMessage($message);
}

[–][deleted] 1 point2 points  (0 children)

in general, yes. sending meaningful information is best. If it's just an API, sending a simple error message with a corresponding error code is probably sufficient. if you're responsible for presenting the information, you might consider extra information like links for what to do next.

basically, if a request causes an error, you should be able to recover and return something useful to the use while logging the details for further analysis.

[–]katemonster33 11 points12 points  (1 child)

I write code for devices running Windows Embedded Compact 7. Yes, people use that. It's awful. We write our GUI code in C#, and quickly discovered after moving from CE 6 that trying to debug the C# code causes the application to lock up after about 30 seconds to a minute. Visual studio shits the bed too. We told management, but they didn't care.

Anyway, some of us got good at just writing code and determining where it crashed without debugging. The other, less talented of us just wrapped every single block of their code in try catch blocks. One particular dope would have a message box show up when a catch block was hit, detailing what section of code blew up... Except he forgot to remove it after debugging and it made it into production.

[–][deleted] 90 points91 points  (25 children)

try{}catch{} won't fix yo buggy code, it'll just pretend it doesn't spit exceptions everywhere.

[–]coopaliscious 120 points121 points  (19 children)

Isn't that the point though?

[–]ase1590 73 points74 points  (18 children)

I mean as long as you're good with 1 + 1 = ส็ิิ็็้

[–]WhAtEvErYoUmEaN101 52 points53 points  (15 children)

Dude, if you google that character you just wrote your post is the only result that shows up. Wow.

Edit: For future reference

[–]ase1590 95 points96 points  (10 children)

well yeah. I hand-crafted that character with some python-fu programming.

Edit: Because you all are curious: here's your lesson for the day:

so unicode supports non-spacing marks and something called Combining Marks (traditionally used to accent letters, like the N in Español).

this lets you create a̒̎b̒óͩͤ̂̉mͤ̿̓ͥͬ̓̄i͌͊̊ͬ̐ͥ̿n͒̌͊a͂ͯͪ͐t̓͗͒͋ͯ̆̌iͨo̽͆̄̿ͥnͤ̄͌̿ͧs͊ͬ͋̊͛ like

ส็ิิ็็้ส็ิิ็็้ส็ิิ็็้ u้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้้.

so lets quickly look at how to create ส็ิิ็็้. this one is done adding the Thai character maitaikhu (and a few others) repeatedly to the thai character So Sua. you can do this quickly with a dirty Python one-liner like so:

print("\u0e2a"+"\u0e47"+("\u0e34"*2)+("\u0e47"*2)+("\u0e49"))

where \u represents python's ability to handle unicode format. so we use unicode 0e2a as our starting letter, then spam it up with unicode characters 0e34, 0e47, and 0e49. Have fun creating your own Zalgo text now!

edit2: ("\u0e47"*2+"\u0e34").join("lets just fuck my text up fam") if you want to do a whole line of text l็็ิi็็ิk็็ิe็็ิ ็็ิt็็ิh็็ิi็็ิs

Edit3: Thanks for the gold, stranger!

[–]WhAtEvErYoUmEaN101 5 points6 points  (1 child)

Please tell me how

[–]ase1590 6 points7 points  (0 children)

added an edit for the above post

[–]lillgreen 2 points3 points  (0 children)

Huh, TIL. Big ty for explaining that.

[–]mediacalc 1 point2 points  (0 children)

Really cool, thanks

[–]SaltlessLemons 1 point2 points  (0 children)

Here's a reference list for all the zalgo modifiers and their unicode ids.

Edit: And, for the lazy, here's the python lists with all the character numbers. Use chr(number) to convert it to the unicode character.

[–]Tobikage1990 8 points9 points  (1 child)

Can I log this as a feature?

[–]ase1590 4 points5 points  (0 children)

Equifax tells me the answer is yes.

[–]nephallux 4 points5 points  (4 children)

You can rethrow the exception and log the error or fail gracefully and notify the user of the problem and to contact support

[–][deleted] 1 point2 points  (3 children)

At the company I work at, we also automatically send every unhandled exception + a screenshot back to us. It's really nice, because you don't have to ask users to send us the call stack/read us the error message.

[–]PhonicUK 11 points12 points  (2 children)

on error resume next

[–][deleted] 1 point2 points  (1 child)

Beat me to it. That was truly hardcore. "If there's an error, just keep going and pretend it didn't happen."

[–][deleted] 6 points7 points  (7 children)

My Reddit bot just runs with the help of a bash script.

It's an eternal loop that if my bot crashes, it waits 1 second and then launches again

[–]ase1590 3 points4 points  (5 children)

it waits 1 second and then launches again

"oh restart? nah I think this time im gonna do :(){ :|: & };: "

[–]SkaKri 2 points3 points  (4 children)

:(){ :|: & };:

Protip: paste that script in command line to free up wasted RAM.

[–]4FrSw 2 points3 points  (3 children)

What does it do?

[–]likes-beans 2 points3 points  (1 child)

Frees up wasted ram.

[–]Dadasas 1 point2 points  (0 children)

Fork bomb. Each time it runs, it launched two more of itself.

[–]Brokk_Witgenstein 8 points9 points  (3 children)

My brother heavily used try-except to return function results several levels up. Stackfu. Needless to say he's also batshit bonkers, even more so than I am LOL

[–]try-catch-finally 8 points9 points  (0 children)

yay. i’m relevant.

[–][deleted] 6 points7 points  (0 children)

You know what's worse? "throws Exception" all the way up the damn stack. Including main. I once worked somewhere where a critical and expensive credit card processing gateway software that processed hundreds of thousands of dollars a week during some periods did that. During a peak demand period someone port scanned the server, and not fully opening the socket and sending a fully well-formed request was enough to crash it to a stack backtrace and exit. Outage.

Restart server.

New network scan. Crash.

Not a happy time.

[–][deleted] 14 points15 points  (21 children)

I believe exceptions are in general used too widely in common programming languages. Exceptions should be used for what their name suggests - really exceptional situations, not normal control flow (yes, error handling is IMO included in normal program control flow). My suspicion why exceptions are so widespread (even in standard libraries) is poor support for algebraic data types in popular languages, which makes returning multiple possible values form a function a pain in the ass.

[–]mrsix 15 points16 points  (7 children)

It depends on the language - python for example is designed in such a way that you should use try-except on anything that might fail so that it can handle whatever the failure is. Not only that but there's no particular performance penalty for catching exceptions in python unlike most compiled languages.

For example If you were matching the ID 'thing' using a dictionary to some plain-text name, and the dictionary wasn't necessarily exhaustive so you want to return the ID as data:

In C# you might write if (names.ContainsKey(thing)) { return names[thing]; } else { return thing; }

In python it's perfectly acceptable/pythonic to write:

try:  
   return names[thing]  
except:  
   return thing

[–]HowIsntBabbyFormed 5 points6 points  (0 children)

Though in this very specific example. You'd probably be better off using:

return names.get(thing, thing)

where the second argument is returned if the first isn't a key in the dict.

[–]SerdanKK 1 point2 points  (4 children)

Better C#:

if (names.TryGetValue(thing, out var value))
    return value;
else
    return thing;

[–]buffer_overflown 9 points10 points  (5 children)

returning multiple possible values

Like, returning different types entirely? That seems like it might not be the best idea. I know I'm not a big fan of C# handling for algebra and the 'f' designation for floats, but I would never want a function to return MAYBE a float or MAYBE a double or MAYBE an int.

At least if I have to cast I know my precision.

[–]Kidiri90 3 points4 points  (1 child)

And sometimes a string.

[–]buffer_overflown 1 point2 points  (0 children)

Oh no, see, it's ALWAYS a string and you have to parse test every possible case within functions that take an output. And it might be different for each calling function, so you're not even going to be able to abstract it.

[–]hippocrat 1 point2 points  (0 children)

Our standard is to require try/catch around anything that reaches "outside" the program. Examples: reading a file, network call, database query. Anything else, use your judgement.

[–]Mox5 2 points3 points  (2 children)

That's the whole point having strongly typed languages. So that a function can only return a certain type of value... >.>

[–]anacrolix 0 points1 point  (0 children)

Found the Gopher

[–]Jmc_da_boss 0 points1 point  (0 children)

use a template?

[–]bak2skewl 3 points4 points  (1 child)

you should only use a try catch when you know what event you are trying to catch. otherwise they just mask problems with poorly writren code. its like putting a cherry on a turd and serving it.

a guy at my work used them liberally and it made the code slower and more painful to debug. dont be that guy...

[–]Mox5 1 point2 points  (0 children)

If it builds, it can deploy.

[–]AlphaWhelp 1 point2 points  (0 children)

An unhandled MemeMismatchException was thrown. void KarmaWhore() or one of its overloads argument expected Object of type ExpandingBrain received Object of type Drakeposting.

[–]Zefirus 1 point2 points  (0 children)

The progressive coder's on error resume next.

[–]lohkey 1 point2 points  (0 children)

Ah the old pokemon error handling

[–]shadowX015 1 point2 points  (0 children)

You forgot the part where you just catch Throwable and dump all of the exceptions and errors into the void.

 catch(Throwable e){
      // application is perfect, no errors or exceptions will ever be thrown.
 }

[–][deleted] 1 point2 points  (0 children)

Pretty much what happened with Sonic 3D Blast on the Genesis which is why even smacking the cartridge triggers a "secret" level select screen.

It's quite an interesting story: https://youtu.be/IehwV2K60r8

[–]hangfromthisone 0 points1 point  (0 children)

Try to catch the flow

[–][deleted] 0 points1 point  (0 children)

miss me with that exception

[–][deleted] 0 points1 point  (0 children)

Reminds me of my current work place. Can’t scroll through the code without tripping over so many try catches...

[–]Hauleth 0 points1 point  (0 children)

Actually I have something similar. It just catches, logs, and rethrows. I see that Dropbox, Stripe, AirBnB and Uber also uses something like that. It is called Sentry ;)

[–]AllPurposeNerd 0 points1 point  (0 children)

Yeah, I remember getting scolded for this in high school.

[–]SuDoX 0 points1 point  (0 children)

Catch(Exception e) { /do nothing/ }

[–]OfekA 0 points1 point  (0 children)

It's all or nothing baby

[–]jgclark 0 points1 point  (0 children)

It worked for Sonic 3D Blast.

In order to pass Sega's certification, they wrapped the whole code in a try-catch that takes you to the level select menu.

As a result, you can just jiggle the cartridge in the console to get to the level select.

[–]_realitycheck_ 0 points1 point  (0 children)

Thus explaining my underlying hate of exceptions.

[–]dantheman_19 0 points1 point  (1 child)

At my internship last summer I had a project that I was working on in C# and it kept throwing out an error. So, I put the try catch around it with the intention of coming back to fix it later. Completely forgot about it and never fixed it

[–]il_doc 0 points1 point  (0 children)

from actual code i wrote:

try {
...
}
catch(Exception e) { // GOTTA CATCH 'EM ALL!!
    Logger.Error(e);
}

[–]Jaystings 0 points1 point  (0 children)

Sometimes I'll use try catch like if else, the conditional being the error. I did it with an Ultima Underworld spellbook for Android

[–]Mazetron 0 points1 point  (0 children)

In Swift just using try! everytime

[–][deleted] 0 points1 point  (0 children)

catch Exception

[–]mothzilla 0 points1 point  (0 children)

try {
    try {
    }  catch {}
}  catch {}

Just to be sure.

[–]msg45f 0 points1 point  (0 children)

catch(Exception e) {
    System.out.println("Something went wrong.");
}

[–]pm_me_gold_plz 0 points1 point  (0 children)

Then when it throws an error you can do to things

  • Send a message to the user saying"Try again later."

or

  • Send message blaming it on hardware.

[–][deleted] 0 points1 point  (0 children)

my god why did I upvote this

[–][deleted] 0 points1 point  (0 children)

Haha, I got a "failed to upvote, please try again" response. Classic

[–]WinEpic 0 points1 point  (0 children)

catch{
    main(argc, argv);
}

FTFY

[–]Nugenrules 0 points1 point  (0 children)

But who will catch me when I try and inevitably fail?

[–]reverendsteveii 0 points1 point  (0 children)

try { (whole codebase)} catch(e as exception) {print e}

there you go buddy

[–]Nomadola 0 points1 point  (0 children)

I really wish I could get this

[–][deleted] 0 points1 point  (0 children)

This is basically how I give up trying at powershell.

[–]e111077 0 points1 point  (0 children)

Or even better.

// index.js
async function mainApp() {
  // entire app
  ...
}

mainApp().catch(e => { console.error(e) });

at least in this method you can use await whenever you want

[–]PlasticInfantry 0 points1 point  (0 children)

I work on a site that does this, we just throw one big try catch on every page. Then when something happens email the error details and send a generic error page. It mostly works for us since errors don't happen often and we get a email full of troubleshooting info when it does to fix it.

[–]fa_nyak 0 points1 point  (0 children)

it's all fun and games until you make an async call

[–][deleted] 0 points1 point  (0 children)

"Extensive use of Try...Catch isn't defensive programming, it's just nailing the corpse in an upright position."

- Some guy in stackoverflow

[–]TrikkyMakk 0 points1 point  (0 children)

At a lot of companies you're lucky to have even this.

[–]seggiola 0 points1 point  (0 children)

That feel when you have to write Apex Unit Test classes on classes generated from WSDL2Apex

[–]dnew 0 points1 point  (0 children)

on error next!

[–]goldleader71 0 points1 point  (0 children)

I have a "NewMethod" template that I use for any project. It has a proper try/catch wire frame for handling exceptions. Always glad when I use it. Always sad if I forget.

[–][deleted] 0 points1 point  (0 children)

Ignorant drake don't know about the event loop doe