Exception Handling C# - how to accept only numbers 1-5, no strings -
so i’m kind of confused how exception handling. have menu created has 5 options, user enters number 1-5. need make exception handler when user enters string or number greater 5. tips? thanks.
do not use exception
handle flow of code unless wish stop abruptly current flow , communicate upper layer of code of 'exceptional' situation need addressed calling code.
in case simple int32.tryparse solve problem. supposing app console application code this
public static void main(string[] args) { displaymenu(); while(true) { int menuchoice; string userinput = console.readline(); if(int32.tryparse(userinput, out menuchoice)) { if(menuchoice >= 1 && menuchoice <= 5) runcommand(menuchoice); else console.writeline("enter number between 1-5"); } else console.writeline("a number between 1-5 required!"); } }
Comments
Post a Comment