SHARE
TWEET

Try Catch - Basic User Input Example

jyoung12387 Feb 17th, 2020 72 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using System;
  2.  
  3. namespace random
  4. {
  5.     class Program
  6.     {
  7.         static void Main(string[] args)
  8.         {
  9.             bool isCorrect = false;
  10.  
  11.             //loop to repeat if user input cannot be parsed
  12.             do
  13.             {
  14.                 Console.Write("Please enter a number: ");
  15.                 string userInput = Console.ReadLine();
  16.  
  17.                 //try catch block to test if user input is correct
  18.                 //if it is it writes result to Console
  19.                 try
  20.                 {
  21.                     int resultAsInt = int.Parse(userInput);
  22.                     Console.WriteLine("\nThe cubed value of {0} is {1}.", resultAsInt, resultAsInt * resultAsInt * resultAsInt);
  23.                     isCorrect = true;
  24.  
  25.                 }
  26.                 catch
  27.                 {
  28.                     Console.WriteLine("Not able to parse. User entered {0}", userInput);
  29.                 }
  30.  
  31.  
  32.             } while (!isCorrect);    //Check to see if input is correct and whether or not to keep looping.
  33.  
  34.             Console.WriteLine("\nProcess Finished");
  35.             Console.ReadLine();
  36.  
  37.         }
  38.  
  39.  
  40.     }
  41. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top