简体   繁体   English

使用try-catch代替if语句

[英]Using try-catch instead of if statement

Currently learning c#. 目前正在学习c#。 Is there any way I could use a try-catch block on the code below instead of an if statement to validate user input? 有什么办法可以在下面的代码中使用try-catch块,而不是if语句来验证用户输入?

string carID = txtCar.Text;
if (carID != "")
{
    car1.car = carID;
}
else
{
    MessageBox.Show("Please enter a car id e.g: ford");
}

For this case use string.IsNullorEmpty 对于这种情况,请使用string.IsNullorEmpty

string carID = txtCar.Text;
if (!string.IsNullorEmpty(carID))
{
    car1.car = carID;
}
else
{
    MessageBox.Show("Please enter a car id e.g: ford");
}

Try and catch statements will slow your program so it is best to use them when necessary. try and catch语句会使您的程序变慢,因此最好在必要时使用它们。 A good example of when to use a try and catch is connecting to a database, also a good time to use throw with it. 何时使用try and catch的一个很好的例子是连接到数据库,也是将throw与数据库一起使用的好时机。 This is because the network could be down and a possible error could occur. 这是因为网络可能会关闭,并且可能发生错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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