首页 \ 问答 \ 我们如何才能轻松找到代码中的哪一行导致运行时异常?(How can we easily find what line in the code causes a runtime exception?)

我们如何才能轻松找到代码中的哪一行导致运行时异常?(How can we easily find what line in the code causes a runtime exception?)

考虑以下分析器:

public void AnalyzeNode(SyntaxNode node, SemanticModel semanticModel, Action<Diagnostic> addDiagnostic, CancellationToken cancellationToken)
{
    var throwStatement = node as ThrowStatementSyntax;

    var isObjectCreationExpression = throwStatement.Expression is ObjectCreationExpressionSyntax;
    var obj = throwStatement.Expression as ObjectCreationExpressionSyntax;

    var isCorrectTypeOfExpression = (obj.Type as IdentifierNameSyntax).Identifier.Text == typeof(ArgumentException).Name;
}

使用SyntaxKind.ThrowStatement作为兴趣种类。

如果抛出的异常没有在new Exception()形式中声明,则obj应该为null ,而是表示为throw e ,其中e是先前声明的异常。

当在之后调用obj.Type时,这反过来将抛出NullReferenceException

有问题的例子:

static void Method1()
{
    throw new ArgumentException();
}

static void Method2(ArgumentException e)
{
    throw e;
}

第一次throw会很好地通过分析器,但第二次throw会导致objnull因为它不是ObjectCreationExpressionSyntax类型。

在沙箱Visual Studio环境中,这将显示为信息消息:

用户诊断分析器'FormattingFixes.EmptyArgumentException.ArgumentExceptionAnalyzer'抛出了一个异常,消息'对象引用未设置为对象的实例。'。

在这个简短的样本中,很容易分辨问题所在,但在一个不那么人为的例子中,它将更难被发现。 行和列都是1 ,没有帮助。

在“传统”编程中,您的环境会自动显示抛出运行时异常的位置以及该时间点的值。 我可以在我的代码中的某个地方放置一个随机断点,每次命中时查看所有值,并尝试从那里推断出它,但是一旦节点数远远高于这些值,这就不能很好地扩展。

我们如何才能轻松找到代码中的哪一行导致运行时异常?


Consider the following analyzer:

public void AnalyzeNode(SyntaxNode node, SemanticModel semanticModel, Action<Diagnostic> addDiagnostic, CancellationToken cancellationToken)
{
    var throwStatement = node as ThrowStatementSyntax;

    var isObjectCreationExpression = throwStatement.Expression is ObjectCreationExpressionSyntax;
    var obj = throwStatement.Expression as ObjectCreationExpressionSyntax;

    var isCorrectTypeOfExpression = (obj.Type as IdentifierNameSyntax).Identifier.Text == typeof(ArgumentException).Name;
}

With SyntaxKind.ThrowStatement as the Kind of Interest.

obj should be null if the thrown exception has not been declared right there in the form new Exception() but is rather presented as throw e where e is a previously declared exception.

This in turn will throw a NullReferenceException when obj.Type is called right after.

Example in question:

static void Method1()
{
    throw new ArgumentException();
}

static void Method2(ArgumentException e)
{
    throw e;
}

The first throw will pass the analyzer just fine, but the second one will cause obj to be null since it is not of type ObjectCreationExpressionSyntax.

In the sandbox Visual Studio environment this will show up as an information message:

The User Diagnostic Analyzer 'FormattingFixes.EmptyArgumentException.ArgumentExceptionAnalyzer' threw an exception with message 'Object reference not set to an instance of an object.'.

In this short sample it's easy to tell where the problem is, but in a less contrived example it will be harder to spot. The line and column are both 1, not helpful.

In "traditional" programming, your environment automatically shows you where the runtime exception was thrown and what the values are at that point in time. I can put a random breakpoint somewhere in my code, look at all values every time it's hit and try to deduce it from there, but this doesn't scale well once the amount of nodes goes much higher than these 2.

How can we easily find what line in the code causes a runtime exception?


原文:https://stackoverflow.com/questions/23093709
更新时间:2023-06-15 16:06

最满意答案

试试这种方式,它会做到这一点

this.weatherProvider.getWeather(
        this.location.city,
        this.location.state
      ).subscribe(weather => {
        this.weather = weather["current_observation"];
        console.log(this.weather);
      }).catch(()=> {

      });

Try this way , it will do the trick

this.weatherProvider.getWeather(
        this.location.city,
        this.location.state
      ).subscribe(weather => {
        this.weather = weather["current_observation"];
        console.log(this.weather);
      }).catch(()=> {

      });

相关问答

更多
  • 正如你在问题中提到的那样 但是,当我更改Xcode中的“代码签名识别”设置以使用我的Apple分发证书并将供应配置文件设置为生产配置文件时,应用程序已成功构建,但当Xcode尝试在iPhone上运行应用程序时,它会引发错误:'应用安装失败。 找不到此可执行文件的有效配置文件'。 您不能直接在设备中使用生产配置文件/证书运行构建,直接从xcode运行,您必须使用开发提供配置文件构建它 如果你想在submisson之前测试你的生产版本,你可以使用TestFlight下载它,那么检查构建将更容易和更好的方法,因为 ...
  • 您的错误让我认为您尝试直接执行TypeScript代码而无需编译(预处理)或动态编译它。 我认为你的代码应该只是ES6。 事实上,使用ES6,您可以获得类支持,但不支持类型支持(例如,在构造函数/方法中)。 我看了一下Ionic2生成器模板,它们似乎是ES6。 看到这个链接: https://github.com/driftyco/ionic2-starter-tabs/tree/master/www 您可以像这样调整您的代码: import {Page, NavController} from 'ioni ...
  • 正如@nickmcblain在评论中所建议的那样,我所要做的就是安装promise-polyfill并且构建工作正常。 just as @nickmcblain suggested in the comments, all I had to do was install promise-polyfill and the build worked.
  • 尝试了一下以下脚本后: # test syntax of all *.php and *.ctp files for file in $(find . -name *.php -or -name *.ctp); do php -l $file; done 但我仍然不明白上面的错误.. After trying a bit the following script worked: # test syntax of all *.php and *.ctp files for file in $(fin ...
  • 我想这是因为你将ANDROID_HOME设置为错误的路径。 ANDROID_HOME必须设置为android SDK的根目录,而不是工具文件夹: SET ANDROID_HOME=C:\adt-bundle-windows-x86_64-20140702\sdk 但工具文件夹必须位于路径中。 SET PATH=%PATH%;%ANDROID_HOME%\tools (当然使用窗口设置来设置环境变量,不要在cmd中执行,这只是为了更清楚地解释) I guess it's because you set A ...
  • 管理修复它,我有两个插件相互冲突,我找到问题的解决方案是创建一个空白项目并逐个重新添加我的插件,直到我看到哪一个有错,然后向后执行相同操作发现另一个有错 这两个插件是离子部署和cordova-plugin-ionic,现在我很清楚这一点 Managed to fix it, I had two plugins colliding with each other, my solution to find the problem was to create a blank project and re-add ...
  • 我的朋友验证了错误堆栈,他发现了一个问题 让我们通过上面错误提到的那条线, 错误:Windows上的文件路径太长,保持在240个字符以下: 所以基本上Windows只允许240个字符限制路径。 所以他更新了项目的路径,最后我们解决了问题。 希望它会帮助别人! My friend verified error stack, and he identified a problem Let us go through line which is mentioned in error above, Error: F ...
  • 试试这种方式,它会做到这一点 this.weatherProvider.getWeather( this.location.city, this.location.state ).subscribe(weather => { this.weather = weather["current_observation"]; console.log(this.weather); }).catch(()=> { }) ...
  • 你的cordova cli版本很旧。 将其更新为6.5.0 npm install -g cordova@latest Your cordova cli version is old. Update it to 6.5.0 npm install -g cordova@latest
  • 700 MB是不够的。 再次重新检查。 它必须是内存溢出错误。 700 mb is not enough. Recheck again. It must will be a memory overflow error.

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。