试接球的最佳练习是什么?
本文关键字:练习 是什么 最佳 | 更新日期: 2023-09-27 18:15:28
我的功能是在有预订请求时保存客户数据。有两种情况:即使客户数据尚未填写,也强制保存预订;或者使用已填写的客户数据保存预订。
如果程序发现这个客户不存在,我执行try catch并向用户抛出异常,以确认用户是否想要创建新的客户数据。如果是,则打开新表单,如果不是,则强制程序保存。
在强制程序保存中,如果存在的话,我想捕获其他异常。
目前,我是这样做的。
try
{
booking = new Booking();
booking.RoomID = roomID;
booking.Tel = txtTel.Text;
booking.PersonalID = txtId.Text;
booking.Name = txtBookBy.Text;
booking.CheckinDate = dtpCheckin.Value;
booking.CheckoutDate = dtpCheckin.Value.AddDays(Convert.ToDouble(cbNight.SelectedItem));
mng.SaveBooking(booking, false);
if (MessageBox.Show("Data is saved") == DialogResult.OK)
{
this.Close();
}
}
catch (NewCustomerException ex)
{
DialogResult dialog = MessageBox.Show("Customer doesn't exist in database. Do you want to create new customer?", "Please confirm", MessageBoxButtons.YesNo);
if (dialog == DialogResult.Yes)
{
String param = txtBookBy.Text + "," + txtTel.Text + "," + txtId.Text;
CustomerForm oForm = new CustomerForm(param);
oForm.Show();
}
else if (dialog == DialogResult.No)
{
try
{
mng.SaveBooking(booking, true);
}
catch (Exception ex1)
{
MessageBox.Show(ex1.Message);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
永远不要使用异常来控制程序的流程。
mng.SaveBooking(booking, false);
应该返回true/false以通知调用代码客户不存在。
最好编写一个方法,只返回这些信息,然后使用这些信息编写以下代码
try
{
// Check if customer already registered
if(mng.CustomerExists(CustomerKey))
{
mng.SaveBooking(booking, false);
if (MessageBox.Show("Data is saved") == DialogResult.OK)
{
this.Close();
}
}
else
{
DialogResult dialog = MessageBox.Show("Customer doesn't exist in database. " +
"Do you want to create new customer?", "Please confirm", MessageBoxButtons.YesNo);
if (dialog == DialogResult.Yes)
{
.....
}
else
{
.....
}
}
}
catch(Exception ex)
{
... somthing unexpected here
}
创建单独的try catch块,这样每个try catch块都有一个单独的职责。在catch块中,您可以管理它抛出异常的语句,并且可以在下一个try catch块中使用该管理语句的结果。
try {
booking = new Booking();
booking.RoomID = roomID;
booking.Tel = txtTel.Text;
booking.PersonalID = txtId.Text;
booking.Name = txtBookBy.Text;
booking.CheckinDate = dtpCheckin.Value;
booking.CheckoutDate = dtpCheckin.Value.AddDays(Convert.ToDouble(cbNight.SelectedItem));
mng.SaveBooking(booking, false);
if (MessageBox.Show("Data is saved") == DialogResult.OK) {
this.Close();
}
}
catch (NewCustomerException ex) {
DialogResult dialog = MessageBox.Show("Customer doesn't exist in database. Do you want to create new customer?", "Please confirm", MessageBoxButtons.YesNo);
}
if (dialog == DialogResult.Yes) {
String param = txtBookBy.Text + "," + txtTel.Text + "," + txtId.Text;
CustomerForm oForm = new CustomerForm(param);
oForm.Show();
}
else if (dialog == DialogResult.No) {
try {
mng.SaveBooking(booking, true);
}
catch (Exception ex1) {
MessageBox.Show(ex1.Message);
}
}
}