c# - Exception handling in return value methods -
i'm working on method should follow logic:
- prompt user enter number console
- try convert input integer
- if successful, return integer
- if unsuccessful, write error message console , restart method
here's have:
static int getplayers() { int players = 0; console.write("how many people playing?"); try { players = convert.toint16(console.readline()); } catch (exception e) { console.write(e.message + "\n" + "----------"); getplayers(); } return players; }
the problem simple, "not code paths return value." can want, it's going have couple ugly conditional statements reflect how of amateur am. i'm looking elegant, professional-grade solution me learn how handle type of logical sequence in future.
thank in advance!
you have return
result of second call of method. if call method without returning value, result 0
(if error has been made).
you players = getplayers()
think it's more elegant because method have one way out.
static int getplayers() { int players = 0; console.write("how many people playing?"); try { players = convert.toint16(console.readline()); } catch (exception e) { console.write(e.message + "\n" + "----------"); return getplayers(); // return result } return players; }
the usage this:
static void main(string[] args) { var players = getplayers(); console.writeline("players count: " + players); console.readline(); }
the output following:
how many people playing?s input string not in correct format. ----------how many people playing?9 players count: 9
Comments
Post a Comment