如果我有一段引发异常的代码,我会收到一条错误消息,但我不知道如何正确捕获(或确定)所引发的异常。通常我会发现System.Exception
这是一个坏主意。
这是一个示例...我正在尝试在不存在的驱动器上创建一个文件夹:
PS <dir> .\myScript.ps1 z:\test
mkdir : Cannot find drive. A drive with the name 'z' does not exist.
At <dir>myScript.ps1:218 char:7
+ mkdir $args[0] 1> $null
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (z:String) [New-Item], DriveNotFoundExc
eption
+ FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.NewItemComm
and
我已经尝试过System.DriveNotFoundException
catch,但是重新运行脚本仍然会产生未捕获的异常。
有什么技巧可以有效地处理任何类型的异常?
运行命令后,立即检查$ error [0]的内容。查看Exception属性,例如:
$error[0] | fl * -force
writeErrorStream : True
PSMessageDetails :
Exception : System.Management.Automation.DriveNotFoundException: Cannot find drive. A drive with the name
'z' does not exist.
at System.Management.Automation.SessionStateInternal.GetDrive(String name, Boolean
automount)
at System.Management.Automation.SessionStateInternal.GetDrive(String name, Boolean
那个特殊的例外是[System.Management.Automation.DriveNotFoundException]
。
顺便说一句,如果您想“捕获”该异常,则需要使用-EA Stop将非终止错误转换为终止错误,以使其生成可以捕获的异常,例如:
PS> try {mkdir z:\foo -ea Stop} catch {$_.Exception.GetType().FUllname}
System.Management.Automation.DriveNotFoundException
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句