Visual Studio 中是否有设置可以在使用可能创建未处理异常的方法时引发警告或错误?

发布于 2024-09-06 15:07:39 字数 411 浏览 1 评论 0原文

基本上在工作中我经常遇到这样的代码:

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

而不是这样的代码:

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

Visual Studio 中是否有一个设置,每当使用诸如 Convert.Double 之类的方法时可以生成警告,该方法可能会引发异常并且该方法未包含在 try{} 块中?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

晨光如昨 2024-09-13 15:07:39

不,没有。部分原因是几乎任何方法都可能抛出异常。它必须对几乎每个方法发出警告,因为几乎任何方法都可能引发以下

  1. StackOverflowException
  2. OutOfMemoryException

在其之上添加更有可能的 NullReferenceException code> 基本上每个方法都会被标记为“可以抛出”。

创建一个标记显式抛出异常的功能是合理的。 VS 没有此功能,但 R# 有 (IIRC)。然而,即使这样也不是万无一失的,因为你无法透过界面看到。

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

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

在同一个方法中可能会或可能不会抛出。在所有情况下都不能通过静态分析来明确确定是否存在。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文