Created
June 29, 2017 05:02
-
-
Save mrcampbell/c1122ab63a46634d33404e4b8a65fcc0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace ExceptionHandlingExample | |
{ | |
using System; | |
public class Program | |
{ | |
public static void Main() | |
{ | |
// Questions I have for you: | |
// #1 Using Exceptions For Logic - What is too much? | |
// #2 Multiple Catch Statements for different Exceptions - What is your rule? | |
// #3 When and how to return - multiple return points? Return within the try/catch/finally or outside? | |
try | |
{ | |
int IntGiven = GetIntBetweenOneAndTen(); | |
PrintIntBetweenOneAndTen(IntGiven); | |
} | |
catch (Exception ex) | |
{ | |
Console.WriteLine("Error: " + ex.Message); | |
} | |
finally | |
{ | |
Console.WriteLine("\nProgram Ended. Press Any Key To Exit..."); | |
Console.ReadKey(true); | |
} | |
} | |
public static int GetIntBetweenOneAndTen() | |
{ | |
int ParsedNumber; | |
string Input; | |
Console.WriteLine("Give me a number between 1 and 10"); | |
Console.Write("> "); | |
try | |
{ | |
// Could throw IO Exception | |
Input = Console.ReadLine(); | |
// Could throw a FormatException Exception | |
ParsedNumber = int.Parse(Input); | |
// Logic or Exception? | |
// as in: | |
if (!IntIsBetweenOneAndTenInclusive(ParsedNumber)) | |
{ | |
throw new ArgumentOutOfRangeException("PROGRAM:MAIN Number Given is Out of Range"); | |
} | |
// or: | |
if (!IntIsBetweenOneAndTenInclusive(ParsedNumber)) | |
{ | |
Console.WriteLine("That number wasn't between 1 and 10 inclusive! Try again.."); | |
} | |
return ParsedNumber; | |
} | |
catch (Exception ex) | |
{ | |
Console.WriteLine("Error: " + ex.Message); | |
return GetIntBetweenOneAndTen(); | |
} | |
} | |
public static void PrintIntBetweenOneAndTen(int IntGiven) | |
{ | |
if (!IntIsBetweenOneAndTenInclusive(IntGiven)) | |
throw new ArgumentOutOfRangeException("PRINT_INT_BETWEEN_1_10: Number out of range. Given: " + IntGiven); | |
Console.WriteLine(IntGiven); | |
} | |
private static bool IntIsBetweenOneAndTenInclusive(int IntToTest) | |
{ | |
return (1 <= IntToTest && IntToTest <= 10); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment