Lets say there is setup like this:
public class MyClass
{
public void DoSomething(string Data)
{
//if (String.IsNullOrWhiteSpace(Data))
//throw new NullReferenceException();
//Do something with Data and let it throw??
}
}
public class EntryPointClass
{
public void DoIt(string Data)
{
var logicClass = new MyClass();
try
{
logicClass.DoSomething(Data);
}
catch(Exception ex)
{
}
}
}
In DoSomething I can detect a problem and throw an exception. In testing EntryPointClass I can test the expected outcome or test that something in happened in the catch.
Why is it better to throw an exception rather than just wait for one to happen? Either way we’ve caught it!
You do both:
The aim is to throw early and provide specific information.
The direct reason to throw here is that the contract with
DoSomething()is broken. Signal it, don’t wait for `DoSomething() to carry on and break other contracts.Fail fast, fail early.