views:

15

answers:

1

Basically at work I commonly run into code like:

double pricediff = 0.0;
if(!string.IsNullOrEmpty(someVariable.ToString()))
    pricediff = Convert.ToDouble(someVariable);

Instead of something like:

double pricediff = 0.0;
Double.TryParse(someVariable, out pricediff);

Is there a setting within Visual Studio that can produce a warning whenever a method such as Convert.Double is used that can throw an exception and the method is not contained within a try{} block?

+1  A: 

No there is not. Part of the reason why is that practically any method out there can throw an exception. It would have to issue a warning for almost every method as virtually any method can raise the following

  1. StackOverflowException
  2. OutOfMemoryException

Add on top of that the much more likely NullReferenceException and essentially every method would be marked as "can throw".

It would be reasonable though to create a feature that marks for explicitly thrown exceptions. VS does not have this feature but R# does (IIRC). However even that is not foolproof because you can't see through interfaces.

interface IExample { 
  void Method(); 
}
class Class1 : IExample() {
  void Method() { throw new Exception(); }
}
class Class2 : IExample() {
  void Method() {}
}

...
IExample v1 = ...;
v1.Method();

In this same Method may or may not throw. Whether it does or not cannot be definitively determined by static analysis in all cases.

JaredPar