-1

I'm making a Tic-Tac-Toe game for an assignment and I am new to C#. I have a custom exception for bad moves called BadMoveException, which would be if the user enters anything other than 0-8. There is existing code for the assignment and I'm wondering if I should do away with the code to create my own to use this exception or if it is easy enough to implement here? Here is the code:

string input;
int position;
do
{
    input = Console.ReadLine();
} 
while (!int.TryParse(input, out position));

I need to catch the BadMoveException, and any others with an unknown error message. Thank you in advance!

maccettura
  • 10,514
  • 3
  • 28
  • 35
PyroGirl8
  • 29
  • 4

2 Answers2

0

As long as your BadMoveException inherits from Exception, then you can use it just like any other Exception, like this:

try {
    //do stuff
    if (badMove) {
        throw new BadMoveException();
    }
} catch (BadMoveException) {
    //user made a bad move!!
} catch {
    //something else went wrong
}

There is more information about exception handling here: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/exceptions/

Gabriel Luci
  • 38,328
  • 4
  • 55
  • 84
0

Here's what I have:

1- First, your exception need to inherit from Exception like this:

public class BadMoveException : Exception { // Your code here }

2- When you have an error, you use it like this:

throw new BadMoveException(// Enter parameter if you have any in you class);

And you catch it:

try
{
    if(Position < 0 || Position > 8) 
    { 
         throw new BadMoveException(// Enter parameter here if you have any);
    }
    else
    {
         // Your code here
    }
}
catch(BadMoveException bmex) { // Show message here }
catch(Exception ex) { // Show other exception }

Hope it helps !

Links for documentation: http://www.tutorialsteacher.com/csharp/custom-exception-csharp https://stackify.com/csharp-exception-handling-best-practices/