Whether it is. NET or Java, in the development process will inevitably use the Throw keyword, for beginners will generally think it and try...catch bundled together, this is certainly wrong, in fact, throw one of the most important role is:
Let the program tell the user something, these things are generally defined before the developer, such as for an input text box, you need to enter a given number, but if the input is not a given range of data, you can tell the user through throw!
Let the program tell the developer something that is generally defined by the underlying developer, and if some business specification is illegal, the program throws an exception to tell the surface developer!
The following is a throw usage in a program:
Copy Code code as follows:
if (VP. ContainsKey ("flag"))
{
int flagvalue;
Int. TryParse (vp["flag"). ToString (), out flagvalue);
Switch (flagvalue)
{
Case 0:
LINQ = Linq. Where (i => i.endtime > DateTime.Now);
Break
Case 1:
LINQ = Linq. Where (i => i.endtime <= datetime.now);
Break
Case 2:
.. break;
Default
throw new ArgumentException ("Incorrect parameters");
}
}
The code above, the foreground user passes in a parameter, this is in the program processing, here does not consider the extension, therefore uses the switch block (for the business changeful situation, we may use the policy pattern, the factory pattern replaces the switch this code bad taste), when you enter the parameter not to the given case condition , an exception is thrown up to tell the user! Of course, the default will be yellow screen appearance, we operate the system, of course, do some processing.
. NET MVC provides us with an instance project that uses the throw keyword to see the code:
Copy Code code as follows:
public bool ValidateUser (string userName, string password)
{
if (String.IsNullOrEmpty (userName)) throw new ArgumentException ("value cannot be null or empty. "," UserName ");
if (string.isnullorempty (password)) throw new ArgumentException ("value cannot be null or empty. "," password ");
Return _provider. ValidateUser (userName, password);
}
Well, for throw's explanation to here, today do the project just use this, so summed up a bit, hoping to bring you a little help, hehe.