Throw new exception
I have seen some people use throw new to participate in business logic in simple functions. For example, the following code:
Catch (exception ex)
{
String error = ex. message;
}
Public object dosomething (string username)
{
Try
{
If (string. isnullorempty (username ))
{
Throw new exception ("the user name cannot be blank ");
}
}
Catch (exception ex)
{
Return ex. message;
}
Return true;
}
After an exception is caught, a new exception is thrown. Before throwing a new exception, you can perform operations on the previously caught exception, such as logging, obtaining exception information, and writing it to the new exception.
Int num = convert. toint32 (textbox1.text );
Try
{
If (num = 0)
{
Throw new argumentnullexception ("0! ");
}
If (num = 1)
{
Throw new exception ("One is displayed! ");
}
}
Catch (argumentnullexception ex)
{
Messagebox. show (ex. message );
}
Catch (exception ex)
{
Messagebox. show (ex. message );
}
Catch is used to handle errors, that is, when an error occurs, the catch part will be executed. Note: it is "when an error occurs ".
However, what do you do if you want to raise an error when no error occurs? You can use the throw statement to manually raise an error.
Throw an exception that should not be thrown
If the above dosomething function is not further encapsulated during catch, it directly throws javasiton to the ui Layer or directly displays it to the customer. If some sensitive data is prompted in the exception stack. For example, the SQL query statement, webservice uri, or post information. This sensitive information should never be known to the customer. exposing this information may cause potential security risks to the system!
3. Make better use of exception
In actual development, since an exception is thrown, we should provide as much useful information as possible about the exception itself. How can we provide more useful information for thrown exceptions? See the following code:
Public static void executecommand (action <idbcommand> action, ref string errmsg)
{
Using (var connection = new sqlconnection ("database tutorial connection string "))
{
Var cmd = connection. createcommand ();
Try
{
Action (cmd );
Cmd.exe cutenonquery ();
}
Catch (dbexception ex) // note that dbexception is caught here
{
Errmsg = ex. message;
Var parameters = new dictionary <string, object> ();
Foreach (sqlparameter p in cmd. parameters)
Parameters. add (p. parametername, p. value );
// Obtain exception-related useful information as much as possible. Here we only use sqlparameter as an example.
// Todo: (save parameters and ex objects or process them further)
}
Catch (exception ex)
{
// Todo other exception handling
}
Finally
{
Cmd. dispose ();
}
}
}