Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should throwing exception be the first thing to do? [closed]

What is the right way (if any...) to validate user input

This one (first throw the exception):

private void DisposeWorkFlowItem(WorkFlowItem item)
{
    if (item == null)
    {
        throw new ArgumentException("work flow item must have value");
    }
    //TO DO: add a call to delete the task from worker service.
    _workFlowItems.Remove(item);
    _workFlowItemsStore.Delete(item);
}

Or this one (first do the action):

private void DisposeWorkFlowItem(WorkFlowItem item)
{
    if (item != null)
    {
        //TO DO: add a call to delete the task from worker service.
        _workFlowItems.Remove(item);
        _workFlowItemsStore.Delete(item);
    }
    else
    {
        throw new ArgumentException("work flow item must have value");
    }
}

Is there any guidelines?

like image 692
Yosi Dahari Avatar asked Feb 03 '26 01:02

Yosi Dahari


1 Answers

There are no real guidelines or rules, but the first one is often preferred, because you can remove the else, removing one level of indention.

private void DisposeWorkFlowItem(WorkFlowItem item)
{
    if (item == null)
    {
        throw new ArgumentException("work flow item must have value");
    }

    //TO DO: add a call to delete the task from worker service.
    _workFlowItems.Remove(item);
    _workFlowItemsStore.Delete(item);
}

Less indention makes for code that is easier to understand, especially in scenarios with multiple such checks.

Oh, and when checking a parameter for null you usually throw an ArgumentNullException with the parameter name as the first parameter:

throw new ArgumentNullException("item");
like image 131
Daniel Hilgarth Avatar answered Feb 05 '26 13:02

Daniel Hilgarth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!