加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如果没有c#异常,如何处理和测试流量控制?

发布时间:2020-12-15 23:27:43 所属栏目:百科 来源:网络整理
导读:如果没有异常,那么处理和测试无效方法的流控制的正确方法是什么?我已经看到微软不推荐这样的做法,那么正确的方法是什么? 这就是我如何处理我的方法中不应该接受的参数: public void RentOutCar(ReservationInfo reservationInfo) { try { if (string.IsNu
如果没有异常,那么处理和测试无效方法的流控制的正确方法是什么?我已经看到微软不推荐这样的做法,那么正确的方法是什么?

这就是我如何处理我的方法中不应该接受的参数:

public void RentOutCar(ReservationInfo reservationInfo) 
    {
        try
        {
            if (string.IsNullOrEmpty(reservationInfo.ReservationNumber) || string.IsNullOrWhiteSpace(reservationInfo.ReservationNumber))
            {
                throw new ArgumentException("Reservation Number is null or empty.");
            }
            if (reservationInfo == null)
            {
                throw new ArgumentNullException("Null Reservation info.");
            }
            if (reservationInfo.Car == null)
            {
                throw new ArgumentNullException("No car registered to rent.");
            }
            if (reservationInfo.RentalDatetime == DateTime.MinValue || reservationInfo.RentalDatetime == DateTime.MaxValue)
            {
                throw new ArgumentException("Rental Date has an unreal value.");
            }
            if (reservationInfo.Car.Mileage <0)
            {
                throw new ArgumentOutOfRangeException("Mileage can't be less than 0.");
            }

            reserverationsRegister.ReservationsDone.Add(reservationInfo);
        }
        catch (Exception) 
        {
            throw;
        }

    }

解决方法

这不是微软在说 you should not control flow with exceptions时的意思.

While the use of exception handlers to catch errors and other events
that disrupt program execution is a good practice,the use of
exception handler as part of the regular program execution logic can
be expensive and should be avoided.

换句话说,在try块中的代码可能抛出并表示合法的程序逻辑的情况下,不应抛出(并随后捕获)异常.

一个用例外控制流程的设计示例可能如下所示:

int x = GetUserInput();
try
{
    MustAcceptPositiveInput(x);
}
catch (InputIsNonPositiveException)
{
    MustAcceptNonPositiveInput(x);
}

等效的“正确”代码可能如下所示:

int x = GetUserInput();
if (x > 0)
{
    MustAcceptPositiveInput(x);
}
else
{
    MustAcceptNonPositiveInput(x);
}

例外情况应保留用于特殊情况,即不属于预期程序执行情况的情况.它会产生更具可读性,更少令人惊讶且性能更高的代码.

您在代码中所做的事情很好(除了@Clay提到的冗余try-catch和错误的测试顺序),您正在验证特殊值的输入,即您的代码无意处理的值.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读