我正试图找到一种方法,用各种可能的异常类型来构建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
包含该内部异常。