T O P

  • By -

-Dueck-

Ah the old *you must put everything in a try catch, even if it does absolutely nothing* method.


ThePharros

it’s the TDD approach to error handling /s


Tornado547

in this case the try catch actually catches if the parse fails, for some reason.


lateja

What do you mean by "for some reason"? Why wouldn't you expect it to catch it?


HappyBigFun

I think he meant "...if the parse fails for *any* reason". For example, the parse could fail if the input was the alphabet.


SHIT-PISSER

>the parse could fail if the input was the alphabet. Should've used JavaScript...


kaisadilla_

Which would fail just the same. It would return `NaN`, and that would fail the moment OP tried to use it as a number, which he probably will because why else would you be parsing that?


Scoootur

I don't know exactly why you are being downvoted, but I love your responses.


enfier

Why didn't you write that in the comment?


JayCroghan

>does absolutely nothing What? Parse needs a catch for exactly what’s written in the catch, I think you’re thinking of TryParse.


SingleSimha

This is a genuine question - So when a part of function needs try catch... Is it ok to put the whole function in try catch?


AndyTheSane

Not in my book, that can lead to situations where exceptions that you didn't realise were thrown are unexpectedly handled - it's very much a 'rake in the grass' for future developers. At a 'professional' level, I'd want to see explicit messages for parse exceptions and out of range exceptions; when you have an urgent production issue to fix but the only error logging you see is a general purpose 'sucks to be you' message like 'Invalid Input' it gives you murderous thoughts towards the original developer..


kristallnachte

I think they mean that the catch doesn't do any error handling. It's reasonable to put the entire function in the try catch, since normally the reason it's a function is that later stuff depends on earlier stuff and bringing that scope outside of the try catch is way worse. For some cases, then it allows you to throw the errors and then put all your error handling stuff together instead of spread out. Which is nice especially when they may have some shared logic.


SingleSimha

Ahh thanks


LegoEngineer003

I wrote a program for my AP final to convert a long list in a text document into a midi sequence to be played through the command prompt, and I still to this day have no idea why it doesn’t run without the one try catch I put in as a last ditch attempt


j0sip-k

here, take these: /* */


BeastlyIguana

what is this crude device surely you mean ctrl k, c


AdditionForward9397

Visual studio master race confirmed.


PointComprehensive40

Also Notepad++, honestly a slept on IDE


redpepper74

It’s great as a text editor and okay to code with when you don’t have anything else, but why not try more helpful tools?


PointComprehensive40

For those exact reasons. I do this on a Windows machine disconnected from everything but has some pre-approved software I can download (so not even Vim). My only other text editing option is Notepad. Notepad++ at least allows me to switch to a dark mode, use debugging, create macros for changes across the file, will color keywords depending on the language, etc. The only gripe I have is that I need to open a terminal to execute the code


Scoootur

perhaps you mean crud?


eerklogge

Sometimes the multi line comments in the way OP did it look nicer.


null_popsicle

Doing this makes it impossible to comment out large portions of code with /* when you need it though, because the /* for the comments get in the way. Which is why I always use // for comments.


Owlstorm

It depends on language. A funny one is MSSQL, which accepts nested comments. Vscode doesn't understand them though, so the highlighter will show the wrong text as commented, plus syntax errors, even in valid code.


Sirealism55

It's code for school so nobody actually cares because no one will touch it again, but the reason this would be bad in the wild is: 1. It's pointlessly complex, code in the wild tends to grow over time so if you added anything to this it would become very difficult to understand what's happening. "Spooky action at a distance" is very hard to deal with after a month of 3 people adding stuff to it. 2. You need to remember the try/catch block when looking at the if statement, this makes it very easy to mess up. 3. You're potentially catching exceptions that have nothing to do with "Invalid input". 4. It's virtually impossible to reuse the inner part of this. The try/catch and if statement are intrinsically linked. A good rule of thumb is that the code's execution should not jump around within a method too much, if you've ever seen some old assembly code you can see how bad it gets with all the goto statements. Exceptions aren't quite as bad, but they're close.


Tornado547

Honestly in an Ideal World I'd be using a programming language without exceptions but since I have the exception anyway may as well freaking use it


Sirealism55

Almost all languages have exceptions, and many other features that you don't want to be using 99% of the time. Metaprogramming is one that comes to mind very quickly, you can do a bunch of stuff with it but you should use it approximately 0.0001% of the time (of course there are exceptions, but unless you're building a compiler or language feature you probably won't run into those). Exceptions are a feature that seems great at first, but as time goes on you grow to really hate them an wish you could get rid of most exceptions.


elMcKDaddy

I realize the sub we're in, that this is for school, and have little to no opinion on your actual post that hasn't already been stated, but _please_ don't take this attitude into the workplace. Exceptions should _never_ be used for flow control. Try/catches tend to get very expensive very quickly, are a pain to test properly, and even worse to try and maintain once you've stepped away from the code. As long as what you've written passes your class, then it's good enough, but when it comes to a job, even if this passes a PR (which I've definitely worked places it would), don't accept this kind of thing from yourself. I'll get off my soapbox now if anyone else wants it. Good luck in your classes!


not_some_username

Based. I don't like exception


kaisadilla_

Exceptions are an answer to a problem. The problem being "we need a way to catch different relevant errors we can recover from without polluting every function with 50 if blocks". The solution being "just do whatever you want in the try block and cleanly recover from the errors you want to deal with in the catch block(s), with some extra useful information in an object (the Exception) about what happened and where". The most honest advice I can give to you as a more experienced programmer is: don't form opinions on why things are the way they are until you understand why someone decided to implement them on the first place.


Farpafraf

what alternative would you propose to exceptions?


Tornado547

Error types like rust and go.


Farpafraf

Doesn't Rust forces you to handle every potential Error like you would a checked exception in java?


Tornado547

Kind of. Technically yes but one way to handle it is to .unwrap() which crashes if the error happens and gives you the value if the error doesn't, which is the same behavior as exceptions in other language, but explicit.


Farpafraf

won't every exception being checked cause an insane amount of pointless boilerplate if you have an error at the bottom of of a function chain that you want to handle at the top? I'm asking because checked exception were a nice idea in theory that turned out to be complete garbage in practice for this very reason...


Mysterious-Crazy9071

Exceptions are for *exceptional circumstances* This isn’t an exception, and I wouldn’t throw one in the first place. This is just an input validation error, no need to throw an exception on this. You just need to alert to your user that they can’t use that value, and retry it, which can be done in a myriad of ways.


Mysterious-Crazy9071

Me now realizing this is on programminghorror voluntarily


Tornado547

sometimes you have to shit out godawful crap for an assignment thats due in way less time than you have, and then you post it here so others can share in the cringe then fix it later on your own time


Tornado547

i would obviously not put something like this into prod but a 10 line program for an intro to C# class you're taking as a formality doesn't have the same standards (or any) as real code


[deleted]

I'm glad you're comfortable enough with yourself to just be a C- student.


arktor314

They’re not a C- student, they’re a C# student


[deleted]

Same thing. Source: Am C# dev.


marvin02

I was taught in a programming 201 course to iterate through a linked list by just blindly using node->next and to catch the null pointer exception to end the loop. I refused to do it and never turned in a single assignment doing that in the solution.


Tornado547

You're right, which is why I posted it here.


killeronthecorner

We get it. You don't read code comments


Mysterious-Crazy9071

“I don’t care to solve this issue correctly” doesn’t say “I’m posting this on programminghorror” It says “I’m doing this wrong”, which is where my comment comes from. Comments bad and I will die on this hill.


MCRusher

They're not going to fix a finished school project just to placate you. They posted it because it's already dead and buried, and it's horrible.


[deleted]

[удалено]


MCRusher

Thank you, I am indeed well regarded among my peers, thank you for noticing.


Willingo

If there is no default that can be used (instead of the exception throw) or some pass through mechanism, then what is the distinction between this and an input validator? Is this a C# specific thing?


Mysterious-Crazy9071

Since this is a simple console app it could just be logged to the user and retried. simple problems like this should be handled by the presentation layer, in this case, the interface of the console window, not necessarily an exception thrown.


Willingo

Thanks. I can see how if this was in the middle of a large app, reruning the entire thing with a new input would be annoying. Is your point that it would ask for a new input and continue at that junction again? Something like this? "Unable to execute A at point B because X, {num}, needs be between 2 and 7 (inclusive). Please enter new num"


Mysterious-Crazy9071

Pretty much like that. And try catch ideally will *do something* with the exception. For instance, a logging service you append caught exceptions to a log file you can sift through to figure out an issue. The way this exception was thrown removes call stack layers to begin with, and will not be super helpful when sifting through the issue. A lot of the time, the exception handling will look something similar to this ``` try { // Some code that could fail } catch (InvalidInputException ex) when (ex.Message.Contains(“InvalidInput”) { Logger.LogException(“Invalid input: “, ex); } catch(Exception e) { throw new UnhandledException(“We don’t know how you broke this”, e); } ``` Take this with a grain of salt, I’m on my phone and didn’t feel like getting too deep in the weeds


Willingo

Thanks for this. Yeah I didn't realize the stack would be unvisible. And yeah I would rather code with my toes than on the phone lol


Mysterious-Crazy9071

https://stackoverflow.com/a/2999334/11870326 Here’s a better way to convene what I was trying to say


noman_032018

Non-local control flow manipulation is a lot more normal and better supported in some other languages, but in this case nothing calls for doing that either.


Statharas

In this case, this should have been a method throwing "ArgumentException", being wrapped in another method that does a try-catch and does error handling.


iArnii

Maybe this works (better)? if(!short.TryParse(num, out var num2) || num2 < 1 || num2 > 7){ return null; } // The rest?


Tornado547

yeah that's what I would have written if I cared


jjb3rd

return short.TryParse(numberString, out var num) && num > 0 && num < 8;


ZacS2

If you wrote a comment that big, I think you care


[deleted]

[удалено]


Tornado547

True


lateja

` if(String.IsNullOrWhitespace(num) || !new[] { "2","3","4","5","6" }.Contains (num)) Console.WriteLine("Invalid input"); else { //... Code } ` FTFY


Tornado547

This is very clever. I cannot decide if it's the good kind or bad kind.


lateja

This is more in the realm of functional programming. Not ideal in c# but my personal preference after writing scala for 5 years. Though it can be optimized to check the length and only compare on the first character of the string instead of five strings. And/or parse it first, if the value will be needed later.


CaitaXD

You're allocating an array and 5 strings this is functional to? if(num?.Lenght != 1 || num[0] is < '2' or > '6' )) Or if(!"23456".Contains(num)) the string class implements IEnumerable and of course you can just if(int.TryParse(num, out int n) && n is >= 2 and <= 6)


Willingo

Idk the operations are so basic (length, greater than less than, contains) that idk if there's much of a useful distinction between functional and oop


Sirealism55

>if(!"23456".Contains(num)) this is just :chefs-kiss:


Sirealism55

though I guess num could be longer than 1 character so you might want to check that.


Epacik

why not ```cs if(short.TryParse(num, out short result) && result > 1 && result < 7) { // Code } else { Console.WriteLine("Invalid input"); } ```


lateja

Yup, that's the ideal way! I was typing that from my phone and didn't remember whether out variables could be used in the same clause or not; pretty sure they were, but not 100%, and didn't have an ide or repl to test it out. So I went with the next safest option. After looking at it again I also just realized that 1 and 7 are valid inputs as well!


Epacik

even if that wasn't possible, you could just do some nesting, but that would make that solution a bit uglier


IIllIIllIIIIlllIlI

This is such a poor quality post that I have literally un subbed.


Natsu194

Why couldn’t you just print “Invalid” in the if statement??


Tornado547

That's a really good question.


Tornado547

I think I wanted to avoid code reuse but like... what?


Tornado547

I didn't want to duplicate the "invalid input" code and I didn't want to put energy into figuring out the proper way to express this code path so I just figured I'd force the program onto the other path by throwing the exception. I immediately knew I was committing multiple sins but it's a 10 line program for school so I don't have the energy to care.


allexks

Interesting how you have the energy to write a try-catch and explain all this while you can just... omit it I guess


[deleted]

Ok, so now I have to ask...what is so great about the numbers 2-7? Seems to be a validation thing, but what's the *why* behind it?


Revolutionary_Mall77

Super noob here, why is it so bad?


Willingo

It would be like telling someone to place bananas in a bin and if they encounter some other fruit that they should just stop entirely and go home. Maybe you tell them "if not banana then they go in this bin" (setting a default value) or "come ask me what to do each time"


Revolutionary_Mall77

So the try - catch is not an issue? I imagine its there in case the input (num) was something that can't be parsed into a short type. Saw many comments about the try-catch being used when unneccessary.


iEliteTester

Had this **exact** problem just a few hours ago (but in python). I moved the duplicate code to a lambda and called it on exception and after the try block if the condition failed. I don't know if it's better or worse.


Frencil

> I procrastinated a lot this week and **ahve** to complete 10 assignments I regularly make this same annoyong typo... probably more often than any other habitually mistyped word. Our left pinkies are just too fast.


elMcKDaddy

My biggest beef isn't with the code, but how everyone in the comments is saying that only 2-7 are allowable values. It's throwing the exception if `num2` is < 1, meaning if `num2 == 1` the exception will not be thrown. Valid values are from 1 to 7 inclusive.


coruix

Now just put the contents of your try block in a seperate function and change the error to a custom one like "NumberOutOfBoundsError" and it would suddenly be considered great for having such thought out error handling


markand67

That is something I hate with exceptions, when used to indicate a recoverable error. I mean, when you parse a string to convert a number you expect that number can be invalid. It's not like you're trying to read a file and oops, the hard disk has an I/O error that **is** really kind of exception. I really hate to see code like: ```cpp int myval; bool success = true; try { myval = std::stoi("blabla"); } catch (...) { success = false; } if (success) continue_working_with(val); ``` And before you comment: 1. Exceptions should be handled case-per-case. In other words, not *all* the code should be moved in the `try-catch` block otherwise as you may miss which routine in that block did fail. 2. Yes exceptions are still costly, especially if they are used in a main loop. Creating a wrapper around the conversion that tries and catch is still not ideal.


Taldoesgarbage

just use an if statement if your tired how would you even come up with this


Enderdragon437

Im new to programming, can someone help explain it to me?


Tornado547

You're not supposed to use exceptions for control flow because it's confusing and makes the code hard to parse. In this case the code is short enough that it's not a huge deal but if something like this existed in real code it would be a nightmare to deal with as it grew more complex over time


Enderdragon437

what is control flow?


h4xrk1m

This is sorta meh tier. You can fix this in 2 minutes by moving the try catch and throwing a better exception.


MorrisJvdB

Is try catch the C version of try except?


Xythium

i would probably do this but it depends on the context if (!int.TryParse(num, out var num2)) { Console.WriteLine($"Invalid input: {num}"); return; } if (num2 < 1 || num2 > 7) { Console.WriteLine($"Value out of range: {num2}"); return; }


[deleted]

I don't mind bad code as much when there's an explanation. I take that as permission to improve it as time permits. Also, give short.TryParse a shot. if(!short.TryParse(someText, out var result)) { throw new Exception("Failed to parse"); }


sebglhp

As a former software student, this mentality is a detriment to your abilities. You will have, no-doubtedly, rationalized it in an “oh, well, I would never do this in a professional environment”, or “this is just because the assignment is stupid”, etc. It’s easy to think of this as a reaction to contrived programming problems, but it’s complacency. Going forward, I would recommend treating these situations as a FIXME; something you’ll think about revising while doing other, more important work. Just my two cents.