简体   繁体   中英

How should I handle unapproriate situations in C#

I'm a beginner and haven't had a job yet, so I never work experience with code. My question is: How should I handle situations, when user enters a value, that doesn't throw exception, but is unacceptable and and program should be closed. Should I throw an exception with some message in catch block, or it would be enough to just show a message ?

Its really up to the requirements of the application that you are developing. But c# has a specific exception type for this:

InvalidArgumentException

And you can use it like this:

if (!ValidateUserInput(input))
    throw new InvalidArgumentException ("input is invalid");

You can then catch that further up in the application and decide how to handle it

It all depends of You. Depends on what You want to achieve.

There is no ultimate answer to this.

It is good to do everything You said. Throw exeption in try catch block and then give a information for user and close program.

Additionally log the error with more informataion to a file or databases.

Message box is good, because is user firendly.

Throw exeption is also good because is very readable for developer - when they read You code they see this is a bad sitiation.

For example what to do:

    try
    {
       if (IsErrorValidation())
       {
            throw new Exeption("You input wrong data");
       }
    }
    catch (Exception e)
    {
      MessageBox.Show("Error" + e.Message );
      CloseProgram();
    }

You create new Exception with Your massage.

Better is create Your own type of Exeption for example ErrorValidationException or use the predefined InvalidArgumentException which exist in C#

        try
        {
           if (IsErrorValidation())
           {
                throw new ErrorValidationException("You input wrong data");
           }
        }
        catch (ErrorValidationException e)
        {
          MessageBox.Show("Error" + e.Message);
          CloseProgram();
        }
        catch (Exeption e)
        {  
           ...
        } 

Then You can use this type of exception later and You can serve this type of exception in a different way

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM