我試圖找到一種方法來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
在上面的案例[DivideByZeroException]中$Error[0]在哪里找到?
因為我在以下屬性的任何地方都找不到它$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 : {}
uj5u.com熱心網友回復:
該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-直接,在這種情況下,$_.Exception合格內部catch塊包含內部例外。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/354130.html
上一篇:獲取列位置(如第一、第二等)
