Can InvalidOperationException be used for static classes? - c#

I'm looking for the appropriate exception to use for each static method in a class library that I have, as all the methods are related.
public static void EnterText(string element, string value, PropertyType elementType)
{
if (PropertiesCollection.Driver == null)
{
throw new InvalidOperationException();
}
if (elementType == PropertyType.Id)
{
PropertiesCollection.Driver.FindElement(By.Id(element)).SendKeys(value);
}
else if (elementType == PropertyType.Name)
{
PropertiesCollection.Driver.FindElement(By.Name(element)).SendKeys(value);
}
else //if elementType does not make sense an argument exception is thrown
{
throw new ArgumentException();
}
}
The problem is if the PropertiesCollection.Driver is not initialized, the method is useless. Therefore, I'd like to throw an exception if it is null when the method is called. The closest thing I have found to what I'm looking for is InvalidOperationException. However MSDN says it is an "exception that is thrown when a method call is invalid for the object's current state". Since it is a static class and thus has no objects, is this an inappropriate exception type? If no, then which exception should be thrown instead?
Also on more of the organizational side of things, should the code snippet that checks if the driver is null be at the top of each method, or is that too redundant? The alternative that I can think of is a helper method called at the beginning of each that checks and throws an exception if need be.

Some people may disagree with me but saying that InvalidOperationException is the wrong exception simply because there's not technically an instance seems like hair-splitting to me. This seems like a perfectly acceptable use of this exception to me.
I suppose you could create a helper function to test for this condition and decide if you should throw the InvalidOperationException but it truthfully doesn't seem all that worthwhile, plus it could, in my opinion, actually decrease the clarity of the code. The check isn't all that much code and, if I'm reading the code, I'd prefer to just see what checks are happening rather than having to dig into another method to figure it out.

Related

Should I check if argument is null if I'm going to use it immediately?

I'm so used to check if a method's argument is null (then proceed to throw an exception) that I almost don't even think about it anymore.
If the argument is a reference type, it's there:
if(arg == null)
throw new ArgumentNullException(nameof(arg));
But what if I'm going to use arg immediately? Should I check anyway? I mean, if I don't, the envinroment will throw for me (a NullReferenceException) anyway.
For instance:
public int DoStuff(object o)
{
return o.GetHashCode();
}
I could write add the null check easily:
public int DoStuff(object o)
{
if(o == null)
throw new ArgumentNullException(nameof(o));
return o.GetHashCode();
}
But in both cases a exception will be thrown (in almost the exact same line, for debugging purpose). The only difference is the type.
The question: On public methods with a single reference type argument, if I'm going to use the argument immediately, should I still check it if it's null?
I suggest checking, because you have two Exception types:
Unexpected NullReferenceException - something went wrong, and you have to debug your own routine
ArgumentNullException - the argument is null, and it's caller that's wrong (and not your code which reacts right)
throwing ArgumentNullException is kind of contract: I'll do the thing in case argument is correct:
// An exaggerated example
public int DoStuff(SomeObject o) {
if (o == null)
throw new ArgumentNullException(nameof(o));
else if (o.Disposed)
throw new ArgumentException(nameof(o), "o must not be disposed")
else if (o.Id > 100)
throw new ArgumentOutOfRangeException("Id ...", nameof(o));
// o meets the contract, we accept it and thus we guarantee the output
return o.SomeMethod();
}
This kind of validation is typical for public (protected) methods since they're exposed to outer world and can face any argument; however, in case of private method you can omit the contract: any caller is within the class that implements the method.
Well, it depends ;)
This is my take on it, and the question is (kinda) subjective.
IMO, if the code throws a NullReferenceException, it means that the code itself has no internal consistency. It is a sign of lazyness and should be avoided at all costs.
If a method throws a NullReferenceException, it is method's fault.
An ArgumentNullException, on the other hand, means that the method cannot "do it's stuff" if the argument is null.
It becomes responsibility of the invoker to guarantee that the parameter is not null, or handle graciously the exception.
Bottom line: an ArgumentNullException is a contract, a NullReferenceException is a bug.
I suppose if you are immediately dereferencing the variable, you could debate either way, but I would still prefer the ArgumentNullException.
It is much more explicit about what is going on. The exception contains the name of the variable that was null, whereas a NullReferenceException does not.
I strongly suggest you check for null at the top of the method.
Think of that as a "contract" that specifies the following:
In order for this method to execute, this argument must be non-null.
Doing the null check is great documentation. You could go one step further an use XML comments e.g.
/// <summary>
///
/// </summary>
/// <param name="arg1"></param>
/// <exception cref="ArgumentNullException">If <paramref name="arg1"/> is NULL.</exception>
private static void Foo(object arg1)
{
}
I'd say it depends more on how you handle the errors, not how they're thrown. An example will help. Imagine this is the method instead of what you have:
public static int DoStuff(string o) {
return Int.Parse(o);
}
If you have this, then it really doesn't matter.
public static void main(string[] args)
{
try {
Console.Write("Enter a number: ");
value = DoStuff(Console.ReadLine());
}
catch(Exception ex) {
Console.WriteLine("An exception was thrown. Contents: " + ex.ToString());
}
}
Either way your program flow is the same. But if you have below:
public static void main(string[] args)
{
try {
int value = 0;
do {
try {
Console.Write("Enter a non-zero number to stop: ");
value = DoStuff(Console.ReadLine());
}
catch(ArgumentException ex) {
Console.WriteLine("Problem with input, try again. Exception message was: " + ex.Message);
continue; // Or just nothing, will still loop
}
} while(value == 0);
}
catch(Exception ex) {
Console.WriteLine("An exception was thrown. Contents: " + ex.ToString());
}
}
Basically, if your error handling doesn't care which exception type it is, then it's just extra code that probably doesn't help you. But if you handle specific things differently, then it may be worth it to test and throw the more specific type of exception.
But I do agree with Dmitry's post above that a public method matters a lot more than a private one. Your signature for the method is somewhat like a contract. It's best to enforce it.
There are a few different scenario's I think you should consider:
The method is called from your own program. You don't expect a null value. You use the object somewhere down the line and if it's null, it will still change the state.
The method is called from your own program. You don't expect a null value. If it's a null, it won't change the state and everything will continue to be consistent.
The method is exposed through a library or API. An unknown developer X calls the method with whatever you want.
You just want to know that an argument is not null while implementing stuff. To protect yourself and your team members.
Points (1) and (2) are about exception safety. Basically this states that regardless of your input, the state of your data structures should be consistent. In most cases this is resolved through a simple check; in more complex scenario's it might involve a rollback or a more complex piece of machinery. So:
If you add a null value to a database, you don't want it to mess up your database. Now, you can of course solve null values by simply checking your assumption. If the argument is null, throw an ArgumentNullException because that best describes the scenario.
If you call a method that doesn't expect a null value and it won't influence the rest of your system, I usually put a comment somewhere and let nature run its course. A NullReferenceException tells me enough about the nature of the bug.
If it's an API, people expect certain behavior (e.g. a ArgumentNullException). Moreover, as a developer you shouldn't trust the big bad outside world so you should check anyways.
If you just want to protect yourself and your team members, use an Assertion. Assertions are usually implemented in such a way, that they don't end up in release code (or at least have no impact on your speed), will automatically trigger a breakpoint and will fail your unit test. They're also easy to recognize so they won't add too much bloat to your code.
To summarize, I wouldn't just put checks everywhere; they tend to make your code unreadable and bloaty. That said, if I would put a check to ensure exception safety, it's best to use the exception that best describes the error.
Follow Einstein - "make things as simple as possible, but no simpler". Does that code do the same thing without a line of code? If so, it is probably best to remove it.

.NET Exception Handling with discrete error codes

I am writing a method (for a service) that returns a specific error code to the client.
Inside this method I am calling various LINQ extension methods. Each one of these extension methods can throw exceptions of 'same' type (say InvalidOperationException), but I need to catch these exceptions individually and return a specific error code. Here is what it looks like now (much simplified version)
public errorCode SomeMethod()
{
try
{
var foo1 = SomeDataSource.Entities1.Single(x=> x.bar1 == somevalue);
}
catch(InvalidOperationException x)
{
return ErrorCode1;
}
try
{
var foo2 = SomeDataSource.Entities2.Single(x=> x.bar2 > somevalue);
}
catch(InvalidOperationException x)
{
return ErrorCode2;
}
......
This is adding up to be a lot of try-catch blocks, as there are several error conditions that can potentially exist. It is also forcing me to elevate the scope of variables like foo to outside the individual try blocks, as they are being used in subsequent try blocks.
I am just curious to see if there is a way to consolidate all this code in a more elegant manner (some inline methods perhaps?) so that it doesn't end up looking so intimidating?
Based on the feed back I got, I have to add that the Business Rules that I am trying to implement leads me to use 'Single' and not 'SingleOrDefault'. Using 'SingleOrDefault' makes it easier because then we can just check for null without catching the exception. 'Single' on the other hand simply throws an exception if the condition fails. Idea here is to consolidate all these try blocks where as somehow keep all the errors happening separate even though every call to 'Single' throws the same type of exception (InvalidOperationException)...
Thanks
You are misusing exceptions for control flow. Better:
var foo1 = SomeDataSource.Entities1.SingleOrDefault(x=> x.bar1 == somevalue);
if (foo1 == null) return ErrorCode1;
Very clean and simple.
What's especially vexing in the original code is that you are treating all occurrences of InvalidOperationException as the same thing. Who knows whether that's true or not?! There can be many things throwing this particular exception type. You might hide bugs by catching too generously. You might even hide EF bugs this way.
If you want to move your business logic into the lambda method, which it sounds like, you can do so by defining an extension.
Note: I am not endorsing the code below at all; I'm just trying to make it fit the question that you have asked.
public static class LinqExtensions
{
public static ErrorCode BusinessSingle(this IEnumerable<TSource> enumerable, Func<TSource, bool> predicate)
{
TSource result;
try
{
result = enumerable.Single(predicate);
return new NoError(); // ????
}
catch
{
return new ErrorOne();
}
}
}
But it would be far better to do one of the following:
If errors are common, then don't treat it like an Exception but rather a validation rule.
If errors are exceptional, then throw Exception that are differentiated.
You're right that if you're always expecting exactly one element to match your condition, you should use Single() rather than SingleOrDefault().
That means that if that is not the case, your system is a faulted state, and your application should shut down because it is not working correctly. By saying Single(), you're saying "I know there's exactly one there. If there's not, there's something seriously wrong."
By trying to handle the exception and return an error code instead, you're saying something different. You're saying "There should be exactly one there, but if there's not, I can do something else to handle that case." That's what SingleOrDefault() is for.

Throwing exceptions for legal states in code

The Exception is a convenient container, that is tempting to use for various purposes. But is it OK to use it for handling legal states in your code?
My example: I have a geometric function that finds the closest object within a search radius:
public IPoint FindNearest(IPoint origin, double searchRadius)
{
}
My idea was that I could throw an exception, when the search doesn't find a hit. But is this a good idea? Alternatively, I could return Null (which I don't like), or return a result object instead of a Point.
Exception, in general, represents an invalid or "exceptional" scenario. In your case, if not finding a hit is an exceptional scenario and it should always be found in usual cases then you can throw exception.
You should always try to avoid throwing exception because of its heavy nature. If caller code is calling this method frequently and your method is in result throwing lot of exceptions, it will make your program slow
Best practice is to use exception only if you can not handle the error in a functial way. In this case not finding a location and returning null is best, because your calling function can handle the null in a functional way. Besides the clean code, throwing and handling exceptions is realy bad for performance, so use them only as last resort.
You could do something like
public bool TryFindNearest(IPoint origin, double searchRadius, out IPoint result)
{
// your logic here, return true if you find a point. Otherwise return false.
}
Then your calling code can do something like:
IPoint nearestPoint;
If (TryFindNearest(origin, searchRadius, out nearestPoint))
{
// do your stuff.
}
Exceptions should be used in invalid scenarios not to control program flow.
Usually in this situation throwing exceptions isn't a good idea, they are expensive and semantically mean something else entirely.
You could return null and do a null check, or I occasionally find that using the Special Case pattern works out nicely and makes for readable code if you give the class/interface a sensible name.
In this instance, you'd return either an implementing class or derived interface called something like:
public class NoHitOnRadius : IPoint {}
And return that from the call when you get no hits. Then the calling code checks the return type:
var p = FindNearest(...);
if (p is NoHitOnRadius)
{
// Do something.
}
Although in this specific situation I'd likely go with the TryFindNearest semantics (to keep commonality with the likes of TryParse etc) that RobH suggests.

Advice on generic try catch

This is not so much of a problem but more feedback and thoughts. I have been considering an implementation for methods that have been tested thoroughly through our internal teams. I would like to write a generic exception catch method and reporting service.
I relize this is not as easy as a "try-catch" block, but allows for a uniform method for catching exceptions. Ideally I would like to execute a method, provide a failure callback and log all the parameters from the calling method.
Generic Try-Execute.
public class ExceptionHelper
{
public static T TryExecute<T, TArgs>(Func<TArgs, T> Method, Func<TArgs, T> FailureCallBack, TArgs Args)
{
try
{
return Method(Args);
}
catch (Exception ex)
{
StackTrace stackTrace = new StackTrace();
string method = "Unknown Method";
if (stackTrace != null && stackTrace.FrameCount > 0)
{
var methodInfo = stackTrace.GetFrame(1).GetMethod();
if (methodInfo != null)
method = string.Join(".", methodInfo.ReflectedType.Namespace, methodInfo.ReflectedType.Name, methodInfo.Name);
}
List<string> aStr = new List<string>();
foreach (var prop in typeof(TArgs).GetProperties().Where(x => x.CanRead && x.CanWrite))
{
object propVal = null;
try
{
propVal = prop.GetValue(Args, null);
}
catch
{
propVal = string.Empty;
}
aStr.Add(string.Format("{0}:{1}", prop.Name, propVal.ToString()));
}
string failureString = string.Format("The method '{0}' failed. {1}", method, string.Join(", ", aStr));
//TODO: Log To Internal error system
try
{
return FailureCallBack(Args);
}
catch
{
return default(T);
}
}
}
}
What I know as draw backs.
Performance Loss using reflection
MethodBase (methodInfo) may not be available through optimization
The try-catch around the error handler. Basically I could use the TryExecute wrapper for the try-catch around the error call back however that could result in a stack overflow situation.
Here would be a sample implementation
var model = new { ModelA = "A", ModelB = "B" };
return ExceptionHelper.TryExecute((Model) =>
{
throw new Exception("Testing exception handler");
},
(Model) =>
{
return false;
},
model);
Thoughts and comments appreciated.
That's a lot of code to put in a catch, including two more try/catch blocks. Seems like a bit of overkill if you ask me, with a good amount of risk that a further exception can obscure the actual exception and that the error information would be lost.
Also, why return default(T)? Returning defaults or nulls as indications of a problem is usually pretty sloppy. If nothing else, it requires the same conditional to be wrapped around every call to the method to check for the return and respond to... some error that has gone somewhere else now.
Honestly, that usage example looks pretty messy, too. It looks like you'll end up obscuring the actual business logic with the error-trapping code. The entire codebase will look like a series of error traps, with actual business logic hidden somewhere in the entanglement of it. This takes valuable focus off of the actual intent of the application and puts something of background infrastructure importance (logging) at the forefront.
Simplify.
If an exception occurs within a method, you generally have two sensible options:
Catch (and meaningfully handle) the exception within the method.
Let the exception bubble up the stack to be caught elsewhere.
There's absolutely nothing wrong with an exception escaping the scope of the method in which it occurs. Indeed, exceptions are designed to do exactly that, carrying with them useful stack information about what happened and where. (And, if you add meaningful runtime context to the exception, it can also carry information about why.)
In fact, the compiler even subtly hints at this. Take these two methods for example:
public int Sum(int first, int second)
{
// TODO: Implement this method
}
public int Product(int first, int second)
{
throw new NotImplementedException();
}
One of these methods will compile, one of them will not. The compiler error will state that not all code paths return a value on the former method. But why not the latter? Because throwing an exception is a perfectly acceptable exit strategy for a method. It's how the method gives up on what it's doing (the one thing it should be trying to do and nothing more) and let's the calling code deal with the problem.
The code should read in a way that clearly expresses the business concept being modeled. Error handling is an important infrastructure concept, but it's just that... infrastructure. The code should practically scream the business concept being modeled, clearly and succinctly. Infrastructure concerns shouldn't get in the way of that.
This is very rarely going to be useful.
It covers only cases where:
The method has a well-defined means of obtaining an appropriate return value in the face of failure.
You'd actually care to log that it happened.
Now, 2 is very common with exceptions of all sorts, but not where 1 is true too.
1 of course is rare, since in most cases if you could produce a reasonable return value for given parameters by means X you wouldn't be trying means Y first.
It also has a default behaviour of returning default(T) - so null or all zeros - if the fallback doesn't work.
This only works where your case 1 above has "something that just returns null as a result because we don't really care very much what this thing does", or where the called method never returns null, in which case you then test for null, which means that your real error-handling code happens there.
In all, what you've got here is a way in which exceptions that would be trappable by real code have to be caught for by testing (and sometimes testing + guesswork) instead, and those that would bring down a program in a clear place with nice debugging information will instead put it into a state where you don't know what's going on anywhere, but at least of the few dozen bugs that got logged before something managed to bring it down fully, one of the is probably the actual problem
When you've a catch on some exception for a particular reason, by all means log the exception. Note that this is not so much to help find bugs (if that exception being raised there is a bug, you shouldn't be catching it there), but to cancel out the fact that having a catch there could hide bugs - i.e. to cancel out the very effect you are deliberately encouraging by putting catches all over the place. (E.g. you expect a regularly hit webservice to fail to connect on occasion, and you can go on for some hours with cached data - so you catch the failure and go on from cache - here you log because if there was a bug meaning you were never trying to hit the webservice correctly, you've just hidden it).
It's also reasonable to have some non-interactive (service or server) app log all exceptions that reach the top of the stack, because there's nobody there to note the exception.
But exceptions are not the enemy, they're the messenger. Don't shoot the messenger.

C# what kind of exception should I raise?

I am currently in a try catch finding if a property has been set properly to the bool value that it should be like this...
public void RunBusinessRule(MyCustomType customType)
{
try
{
if (customType.CustomBoolProperty == true)
{
DoSomething();
}
else
{
throw new Exception("This is obviously false or possibly null lets throw up an error.");
}
}
catch(Exception)
{
throw;
}
}
Now the deal with throwing this error for me is that I am using Microsoft's source analysis and it gives me an error stating "CA2201 : Microsoft.Usage : Object.RunBusinessRule(MyCustomType)creates an exception of type 'Exception', an exception type that is not sufficiently specific and should never be raised by user code. If this exception instance might be thrown, use a different exception type.
Soooo What exception should I throw that would be specific enough for Microsoft.., for the circumstance of throwing an error about my own application's logic handling and when I want to "throw".
ArgumentException
InvalidOperationException
FormatException
The passed in argument wasn't good.
Create your own exception extending Exception. E.g.: RuleViolationException
Should you be throwing an exception at all?
Having a false boolean value isn't exactly an exceptional circumstance.
EDIT
My original answer was a bit terse so I'll elaborate...
From your example it's not clear what the actual objects, properties and methods represent. Without this information, it's difficult to say what type of exception, if any, is appropriate.
eg, I'd consider the following a perfectly valid use of an exception (and your real code might well look something like this, but we can't tell from your example):
public void UpdateMyCustomType(MyCustomType customType)
{
if (!customType.IsUpdateable)
throw new InvalidOperationException("Object is not updateable.");
// customType is updateable, so let's update it
}
But in the general case, without knowing more about your domain model, I'd say that something like this (a false boolean value) isn't really exceptional.
ArgumentException maybe?
A case could be made for InvalidOperationException, too.
The answer here is that you shouldn't throw any exception. Why throw an exception just to catch it again in a second and rethrow it?
A slight aside, but you could simplify your code somewhat...
public void RunBusinessRule(MyCustomType customType)
{
if (customType.CustomBoolProperty == false)
{
throw new Exception("This is obviously false or possibly null lets throw up an error.");
}
DoSomething();
}
As for the type of exception to throw, you might consider ApplicationException or InvalidOperationException, or you could define your own exception type.
I know that a question is about throwing an exception but I think it would be more appropriate to do an assertation here:
// Precondition: customType.CustomBoolProperty == true
System.Diagnostics.Debug.Assert(customType.CustomBoolProperty)
DoSomething();
InvalidArgument exception is fine but better yet, an ApplicationException.
The other answers are fine for quick resolution, but ideally if you know at compile time that a certain method should never be invoked using certain parameters, you can prevent that from ever happening by inheriting your custom type, instanciating it only when that custom bool is true, and now your method looks like.
public void RunBusinessRule(MyInheritedType inheritedObject)
{
//No need for checks, this is always the right type.
//As a matter of fact, RunBusinessRule might even belong to MyInheritedType.
}
This is the I in SOLID.
I think you should avoid exceptions for code logic.
I suggest to modify your method to return the result of your method as a bool type then you may decide the appropriate way to show an error message to the user at the time of calling the method:
public bool RunBusinessRule(MyCustomType customType)
{
try
{
if (customType.CustomBoolProperty == true)
{
DoSomething();
return true;
}
return false;
}
catch(Exception)
{
throw;
}
}
Make your own custom exception by extending System.Exception and throw that. You can get even crazier and have a whole tree of exception types if you want.
You could just create a custom ValidationException that is only used for your business logic validation. Or you could create a separate validation exception for each type of validation error although that is probably overload.
Not really what you were asking for, but there are plenty of people who have already given answers that I agree with, but you should also avoid only using catch(Exception ex).
It is a much better practice to try to catch the specific Exceptions that are possible first and if need be, catch the generic Expception. eg:
try{
MyMethod(obj);
}catch (NullReferenceException ne){
//do something
}
catch(UnauthorizedAccessException uae){
//do something else
}
catch(System.IO.IOException ioe){
//do something else
}
catch(Exception){
//do something else
}

Categories