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实例存储在$Error[0]中存储的System.Management.Automation.ErrorRecord实例的.Exception属性值的.InnerException属性中,反映了最近的错误:

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包含该内部异常。

最新更新