Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What type of exception to throw

Tags:

c#

exception

What typeo of exception would you throw from a readonly property when the object that is being used to return value is null

public class TestClass
{
    SomeObject obj;
    public string NameOfObject 
    {
       get 
       {
            if(obj == null)
            { // what exception type to throw here  }
            return obj.Name;
       }
}
like image 630
Sheraz Avatar asked Jan 07 '11 15:01

Sheraz


People also ask

What kind of exception will be thrown?

We can throw either checked or unchecked exceptions. The throws keyword allows the compiler to help you write code that handles this type of error, but it does not prevent the abnormal termination of the program.

What type of exception should I throw Java?

Only checked exceptions are required to be thrown using the throws keyword. Unchecked exceptions don't need to be thrown or handled explicitly in code.

What are the 3 types of exceptions?

There are three types of exception—the checked exception, the error and the runtime exception.


3 Answers

I would throw an InvalidOperationException.

ArgumentNullException i only throw if methods parameters are null.

If the methods parameter is in an invalid state i throw an ArgumentException.

like image 52
Khh Avatar answered Oct 11 '22 19:10

Khh


An InvalidOperationException is what I would use in this case, because the access to the property is not valid for the current state of the object.

According to MSDN documentation:
"The exception that is thrown when a method call is invalid for the object's current state."
also:
"InvalidOperationException is used in cases when the failure to invoke a method is caused by reasons other than invalid arguments."

In this case obj is not an argument, which is why I would lean towards "InvalidOperationException"

The reason why I would not throw a NullReferenceException here: If you didnt add any special code, thats the exception that ".Net" would throw, so why add redundant code?

like image 30
Raj Rao Avatar answered Oct 11 '22 20:10

Raj Rao


You should not throw NullReferenceException. It is reserved for situations when a null object is dereferenced. In this case, if you were to throw NullReference, you might as well just leave the null check out and let the framework throw it for you when you attempt to access the obj's Name.

I'd throw InvalidOperationException instead.

like image 35
Adam Lear Avatar answered Oct 11 '22 20:10

Adam Lear