在方法开始和结束时进行错误处理的优缺点是什么 [英] What are the pros and cons of error handling at beginning vs. end of the method

查看:56
本文介绍了在方法开始和结束时进行错误处理的优缺点是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据我的程序员的经验,我在所有可能的方式上都混合了错误处理...我创建了个人风格.

In my programmer's experience, I have mixed error handling all the ways possible... I have created my personal style.

但是,我想听听在方法的开始还是结束时,您认为错误处理的优缺点.

开始处理:

public String GenerateSomeStringData(String data, int value)
{
    if (data == null)
        throw new ArgumentNullException("data");

    if (value <= 0)
        throw new ArgumentException("value must be greater than zero");

    int dataValue;
    if (!int.TryParse(data, out dataValue))
        throw new InvalidOperationException("data does not contain an integer");

    return dataValue * 4 + value / 12;
}

最后处理:(相同的示例)

public String GenerateSomeStringData(String data, int value)
{
    if (data != null)
    {
        if (value > 0) 
        {
            int dataValue;
            if (int.TryParse(data, out dataValue))
            {
                return dataValue * 4 + value / 12;
            }
            else 
                throw new InvalidOperationException("data does not contain an integer");
        }
        else 
            throw new ArgumentException("value must be greater than zero");
    }
    else 
        throw new ArgumentNullException("data");
}

在决定如何处理此问题时,您使用什么标准?可读性,可维护性,简洁性?

What criteria do you use when deciding how to approach this? Readability, maintainability, brevity?

推荐答案

输入有效期应为前提条件执行该方法-这样,我会(并且会一直)首先首先进行错误处理.

Validity of input should be a precondition for execution of the method - as such I would (and do) always do the error handling first.

这具有以下优点:

  • 对于人类而言,解析起来更容易:先验证先决条件,然后再验证执行逻辑(通常是导致某些后期情况)

  • It is easier to parse for a human: validating preconditions first, then execution logic (which usually results in some post condition)

清除关注点之间的分离错误处理和执行逻辑
在您的方法中:验证逻辑未散布"在执行逻辑中

Clear separation of concerns between error handling and execution logic
within your method: validation logic is not "sprinkled in" within the execution logic

如评论中所述,您必须区分违反先决条件并触发错误条件(例如引发异常)的无效输入和构成边沿条件(即需要一些边缘条件)的有效输入特殊逻辑来处理).在确定前提条件之后,我将在方法的执行逻辑开始时分别处理后一种情况.

As mentioned in the comments you have to differentiate between invalid input that violates a precondition and triggers an error condition (such as throwing an exception) and valid input that constitutes an edge condition (i.e. requiring some special logic to handle). The later case I would handle separately after asserting the preconditions, at the beginning of the execution logic of your method.

这篇关于在方法开始和结束时进行错误处理的优缺点是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆