[英]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.