繁体   English   中英

PowerShell tr​​y catch 中的异常类型详细信息不匹配

[英]Exception type details not matching in PowerShell try catch

我试图找到一种方法来构建具有各种可能的异常类型的try catch块。 我从其他问题中得到了一些线索来检查$Error[0].Exception.GetType().FullName

但是,我仍然无法弄清楚从哪里获取必须放在catch关键字前面的 Exception 类类型。

例如,当我尝试:

try { 1/0 } catch { $Error[0].Exception.GetType().FullName }

我得到:

System.Management.Automation.RuntimeException

但是,当我在下面运行时:

try { 1/0 } catch [DivideByZeroException]{ "DivideByZeroException" } catch { $Error[0].Exception.GetType().FullName }

我得到:

DivideByZeroException

在上述情况下, $Error[0]中的[DivideByZeroException]在哪里?

因为我在$Error[0]的属性中找不到它:

PS C:\Temp> $Error[0] | Select *


PSMessageDetails      : 
Exception             : System.Management.Automation.RuntimeException: Attempted to divide by zero. 
                        ---> System.DivideByZeroException: Attempted to divide by zero.
                           --- End of inner exception stack trace ---
                           at System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(
                        FunctionContext funcContext, Exception exception)
                           at System.Management.Automation.Interpreter.ActionCallInstruction`2.Run(Int
                        erpretedFrame frame)
                           at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction
                        .Run(InterpretedFrame frame)
                           at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction
                        .Run(InterpretedFrame frame)
TargetObject          : 
CategoryInfo          : NotSpecified: (:) [], RuntimeException
FullyQualifiedErrorId : RuntimeException
ErrorDetails          : 
InvocationInfo        : System.Management.Automation.InvocationInfo
ScriptStackTrace      : at <ScriptBlock>, <No file>: line 1
PipelineIterationInfo : {}

所述DivideByZeroException实例中存储在.InnerException所述的属性.Exception所述的属性值System.Management.Automation.ErrorRecord保存在实例$Error[0]这反映了最新的错误:

PS> try { 1 / 0 } catch {}; $Error[0].Exception.InnerException.GetType().FullName

System.DivideByZeroException

也就是说, RuntimeException包装DivideByZeroException异常。

看起来,因为您使用的是类型限定的catch块,在该catch块中, 自动$_变量中反映的[ErrorRecord]实例直接.Exception包含指定的异常 - 与自动$Error中的相应条目不同变量

PS> try { 1 / 0 } catch [DivideByZeroException] { 
      $_.Exception.GetType().FullName; 
      $Error[0].Exception.GetType().FullName 
    }

System.DivideByZeroException                  # type of $_.Exception
System.Management.Automation.RuntimeException # type of $Error[0].Exception

换句话说:

  • 在未限定的catch块中, $_等价$Error[0] (后者也可以在以后访问),并且包含.Exception中的(外部)异常和 - 如果适用 - .Exception.InnerException的内部异常。

  • 类型限定的catch块中,您可以直接捕获内部异常 - 正如(稍后)反映在$Error[0].Exception.InnerException -直接,在这种情况下,限定的catch块中的$_.Exception包含该内部异常.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM