views:

96

answers:

5

I am confused. Whether to create a custom exception or .Net base class library has the relevant exception?

I am calling some kind of service or framework API and it returns back a null reference which is an exceptional case for my tier. I know that the system won't be able to proceed with null reference and I should get a NullReferenceException down the line if I proceed.

So, should I create a custom exception at that point or should I wait to occur the NullPointerReference?

See the code snippet below



Organization organization = OrganizationService.GetOrganizationById("123");
this.SetOrders(organization.Id); // This will give me NullReferenceException

please guide me.

Thanks and regards

123Developer

+3  A: 

In general, its good practice to catch errors as soon as possible and handle them in the best manner possible - either by using default values to work around the error, or informing the user that you cannot proceed.

So in this specific case, if i understand correctly, i would test the variable for null, and if its null do not continue - bail out gracefully.

cyberconte
+1  A: 

I often design a DataNotFoundException that is thrown when a get-operation based on an object ID fails. My rationale for doing so is that ID's are typically not entered by the user, but used only in the code, so if a search is performed using a non-existing ID the input is bad, and I want to signal that in a clear manner.

Fredrik Mörk
+2  A: 

NullPointerReference exceptions are always hard to debug and should be avoided whenever possible. In certain cases you could use ArgumentNullException, if the "null" value is one of the passed parameters. Not in your case though and that's where I would recommend a custom exception.

Filip Navara
+2  A: 

Throw an InvalidOperationException if it has nothing to do with any arguments passed to your method, or an ArgumentException otherwise. Do this as soon as is reasonably possible, to avoid accidentally corrupting your state.

Aside from anything else, this allows you to give a more useful message, indicating what couldn't be found.

Jon Skeet
+2  A: 

Hi, as a general rule you should only catch exceptions down the stack if you can add meaning to the exception itself.

In your particular case, I would suggest that you check the value for null, and throw an appropriate exception yourself (possibly an InvalidOperationException with a message of "Organization not found"?)

Sklivvz