捕获未处理的异常
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了捕获未处理的异常相关的知识,希望对你有一定的参考价值。
我试图捕获powershell使用Windows窗体生成的未处理的异常;
目前我能够使用try / catch捕获终止错误,并且已经研究了几个帖子,但仍然显示了未处理的异常错误框,我想不显示。
试试Catch,似乎没有帮助
Function Get-Choice{
Try{
$ErrorActionPreference = 'Stop'
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
$Form3 = New-Object System.Windows.Forms.Form
$Form3.Text = "Please Make A Choice From Below"
$Form3.ClientSize = New-Object System.Drawing.Size(390, 160)
$form3.topmost = $true
$Text = New-Object System.Windows.Forms.Label
$Text.Location = New-Object System.Drawing.Point(15, 15)
$Text.Size = New-Object System.Drawing.Size(300, 80)
$Text.Text = "What would you like to do today? `n`n 1. Find the Permissions of a folder `n 2. Find Who Has Access to a Folder `n 3. Find out what shares are on a server`n 4. Select a csv that contains a list of shares"
$Form3.Controls.Add($Text)
#$ErrorActionPreference = "SilentlyContinue"
Function Button1
{
$Button1 = New-Object System.Windows.Forms.Button
$Button1.Location = New-Object System.Drawing.Point(15, 100)
$Button1.Size = New-Object System.Drawing.Size(125, 25)
$Button1.Text = "1. Folder Permissions"
$Button1.add_Click({Folder
$Form3.Close()})
$Form3.Controls.Add($Button1)
}
Function Button2
{
$Button2 = New-Object System.Windows.Forms.Button
$Button2.Location = New-Object System.Drawing.Point(145, 100)
$Button2.Size = New-Object System.Drawing.Size(100, 25)
$Button2.Text = "2. Folder Access"
$Button2.add_Click({Members
$Form3.Close()})
$Form3.Controls.Add($Button2)
}
Function Button3
{
$Button3 = New-Object System.Windows.Forms.Button
$Button3.Location = New-Object System.Drawing.Point(250, 100)
$Button3.Size = New-Object System.Drawing.Size(130, 25)
$Button3.Text = "3. Shares on a Server"
$Button3.add_Click({Shares
$Form3.Close()})
$Form3.Controls.Add($Button3)
}
Function Button4
{
$Button4 = New-Object System.Windows.Forms.Button
$Button4.Location = New-Object System.Drawing.Point(145, 128)
$Button4.Size = New-Object System.Drawing.Size(100, 25)
$Button4.Text = "4. Auto Shares"
$Button4.add_Click({Auto
$Form3.Close()})
$Form3.Controls.Add($Button4)
}
Button1
Button2
Button3
Button4
[void]$Form3.showdialog()
}
Catch[System.Exception]{
}
}
}
Get-Choice
未显示未处理的异常对话框,但脚本终止
答案
将您调用的函数包含在try-catch
-Blocks中的Click事件中以“处理”异常:
Function Button1
{
$Button1 = New-Object System.Windows.Forms.Button
$Button1.Location = New-Object System.Drawing.Point(15, 100)
$Button1.Size = New-Object System.Drawing.Size(125, 25)
$Button1.Text = "1. Folder Permissions"
$Button1.add_Click({
Try{
Folder
}catch{<# Maybe something here #>}
$Form3.Close()})
$Form3.Controls.Add($Button1)
}
另一答案
所以通过使用return代替exit代码并编写try catch来解决这个问题,
谢谢你的帮助@T-Me
以上是关于捕获未处理的异常的主要内容,如果未能解决你的问题,请参考以下文章
编写高质量代码改善C#程序的157个建议——建议65:总是处理未捕获的异常
启用“仅我的代码”时,Visual Studio 2015 JavaScript 调试不会捕获未处理的异常