Exception Handling – Should You Throw Exceptions or Let Code Fail?

exceptions

I am wondering if there are any pros and cons against this style:

private void LoadMaterial(string name)
{
    if (_Materials.ContainsKey(name))
    {
        throw new ArgumentException("The material named " + name + " has already been loaded.");
    }

    _Materials.Add(
        name,
        Resources.Load(string.Format("Materials/{0}", name)) as Material
    );
}

That method should, for each name, be run only once. _Materials.Add() will throw an exception if it will be called multiple times for the same name. Is my guard, as a result, completely redundant, or there are some less obvious benefits?

That's C#, Unity, if anyone is interested.

Best Answer

The benefit is that your "custom" exception has an error message that's meaningful to anyone calling this function without knowing how it's implemented (which in the future might be you!).

Granted, in this case they'd probably be able to guess what the "standard" exception meant, but you're still making it clear that they violated your contract, rather than stumbled across some strange bug in your code.

Related Topic