In the following example we have two different exceptions we want to communicate.
//constructor
public Main(string arg){
if(arg==null)
throw new ArgumentNullException("arg");
Thing foo=GetFoo(arg);
if(foo==null)
throw new NullReferenceException("foo is null");
}
Is this the proper approach for both exception types?
The first exception is definitely correct. It’s the second one which is tricky.
There are two possibilities here:
GetFoo()isn’t meant to return null, ever. In that case we’ve basically proven a bug inGetFoo(). I’m not sure of the best exception here, leavingContractException(from Code Contracts) aside. Basically you want something likeContractException– an exception which means “The world has gone crazy: this isn’t just an externally unexpected result, there’s a bug here.”GetFoo()can legitimately returnnull, due toarg‘s value. In this case I would suggest thatArgumentException(but notArgumentNullException) may be appropriate. On the other hand, it’s odd to throwArgumentExceptionafter using the argument.InvalidOperationExceptionisn’t quite appropriate here, but I might be tempted to use it as the closest thing to a contract failure…EDIT: You should also consider creating your own exception, as per Aaronaught’s answer.