解析Catch表达式中声明的异常类型

本文关键字:异常 类型 声明 Catch 表达式 解析 | 更新日期: 2023-09-27 18:03:17

我一直在研究一些Roslyn代码分析器。我的目标是分析异常和Catch块。

当我能够分析节点并获得节点可能抛出的每个ExceptionNamedType时,我遇到了一种情况。同时,我能够枚举与该节点相关的所有Catch块。

我需要解析给定的NamedType是否等于Catch表达式声明或其基类。

说明代码:

var typeName = "System.ArgumentNullException";
NamedType exceptionType = _compilatorStartContext.Compilation.GetTypeByMetadataName(typeName);
// exceptionType = NamedType System.IO.IOException
var tryStatement = arg as TryStatementSyntax;
CatchDeclarationSyntax @catch = tryStatement.Catches.First();
var declaration = @catch.Declaration;
// declaration = CatchDeclarationSyntax CatchDeclaration (Exception)
// TODO: decide whether declaration can be instantiated from exceptionType

解析Catch表达式中声明的异常类型

您需要使用语义模型。

在你得到它之后,你可以这样做:

// var declaredType = analysisContext.SemanticModel.GetDeclaredSymbol(@catch.Declaration).Type;
// ^^ only works on catch(FooException x), doesn't work on catch (FooException) 
var declaredType = analysisContext.SemanticModel.GetTypeInfo(@catch.Declaration.Type);
var implements = false;
for (var i = declaredType.Type; i != null; i = i.BaseType)
{
    if (i == exceptionType)
    {
        implements = true;
        break;
    }
}
// implements holds the result