ThreadExceptionEventArgs Classe
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Fornece dados para o ThreadException evento.
public ref class ThreadExceptionEventArgs : EventArgs
public class ThreadExceptionEventArgs : EventArgs
type ThreadExceptionEventArgs = class
inherit EventArgs
Public Class ThreadExceptionEventArgs
Inherits EventArgs
- Herança
- Derivado
Exemplos
O exemplo seguinte permite-lhe criar um ThreadException evento clicando button1 num formulário. O exemplo cria duas classes. A ErrorHandler classe cria o formulário e o botão que levanta o evento. A CustomExceptionHandler classe fornece os métodos para lidar com a exceção.
Em Main na ErrorHandler classe, o código cria uma nova instância da classe de tratamento de exceções, ou seja, uma instância do CustomExceptionHandler. Depois, a instância é adicionada ao evento e a aplicação é executada.
No OnThreadException método da CustomExceptionHandler classe, o exemplo usa uma try...catch...finally instrução para processar a exceção. O ShowThreadExceptionDialog método cria a mensagem para mostrar e apresenta-a numa caixa de mensagem.
using System;
using System.Threading;
using System.Windows.Forms;
// Create a form with a button that, when clicked, throws an exception.
public class ErrorForm : System.Windows.Forms.Form
{
internal Button button1;
public ErrorForm() : base()
{
// Add the button to the form.
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
this.button1.Location = new System.Drawing.Point(100, 43);
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.Text = "Click!";
this.Controls.Add(this.button1);
this.button1.Click += new EventHandler(this.button1_Click);
this.Text = "ThreadException";
this.ResumeLayout(false);
}
// Throw an exception when the button is clicked.
private void button1_Click(object sender, System.EventArgs e)
{
throw new ArgumentException("The parameter was invalid");
}
public static void Main()
{
// Add the event handler.
Application.ThreadException += new ThreadExceptionEventHandler(CustomExceptionHandler.OnThreadException);
// Start the example.
Application.Run(new ErrorForm());
}
}
// Create a class to handle the exception event.
internal class CustomExceptionHandler
{
// Handle the exception event
public static void OnThreadException(object sender, ThreadExceptionEventArgs t)
{
DialogResult result = ShowThreadExceptionDialog(t.Exception);
// Exit the program when the user clicks Abort.
if (result == DialogResult.Abort)
Application.Exit();
}
// Create and display the error message.
private static DialogResult ShowThreadExceptionDialog(Exception e)
{
string errorMsg = "An error occurred. Please contact the adminstrator " +
"with the following information:\n\n";
errorMsg += string.Format("Exception Type: {0}\n\n", e.GetType().Name);
errorMsg += "\n\nStack Trace:\n" + e.StackTrace;
return MessageBox.Show(errorMsg, "Application Error",
MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop);
}
}
Imports System.Threading
Imports System.Windows.Forms
' Create a form with a button that, when clicked, throws an exception.
Public Class ErrorForm : Inherits Form
Friend WithEvents button1 As Button
Public Sub New()
' Add the button to the form.
Me.button1 = New System.Windows.Forms.Button()
Me.SuspendLayout()
Me.button1.Location = New System.Drawing.Point(100, 43)
Me.button1.Size = New System.Drawing.Size(75, 23)
Me.button1.Text = "Click!"
Me.Controls.Add(Me.button1)
Me.Text = "ThreadException"
Me.ResumeLayout(False)
End Sub
' Throw an exception when the button is clicked.
Private Sub button1_Click(sender As Object, e As System.EventArgs) _
Handles button1.Click
Throw New ArgumentException("The parameter was invalid.")
End Sub
Public Shared Sub Main()
' Add the event handler.
AddHandler Application.ThreadException,
AddressOf CustomExceptionHandler.OnThreadException
' Start the example.
Application.Run(New ErrorForm())
End Sub
End Class
' Create a class to handle the exception event.
Friend Class CustomExceptionHandler
'Handle the exception event.
Public Shared Sub OnThreadException(sender As Object, t As ThreadExceptionEventArgs)
Dim result As DialogResult = ShowThreadExceptionDialog(t.Exception)
' Exit the program when the user clicks Abort.
If result = DialogResult.Abort Then
Application.Exit()
End If
End Sub
' Create and display the error message.
Private Shared Function ShowThreadExceptionDialog(e As Exception) As DialogResult
Dim errorMsg As String = "An error occurred. Please contact the " &
"adminstrator with the following information:" &
vbCrLf & vbCrLf
errorMsg &= "Exception Type: " & e.GetType().Name & vbCrLf & vbCrLf
errorMsg &= e.Message & vbCrLf & vbCrLf
errorMsg &= "Stack Trace: " & vbCrLf & e.StackTrace
Return MessageBox.Show(errorMsg, "Application Error",
MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop)
End Function
End Class
Observações
A ThreadExceptionEventArgs é criado por um thread quando ocorre uma exceção não tratada. ThreadExceptionEventArgs contém o Exception que ocorreu.
Construtores
| Name | Description |
|---|---|
| ThreadExceptionEventArgs(Exception) |
Inicializa uma nova instância da ThreadExceptionEventArgs classe. |
Propriedades
| Name | Description |
|---|---|
| Exception |
Percebe que Exception isso aconteceu. |
Métodos
| Name | Description |
|---|---|
| Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual. (Herdado de Object) |
| GetHashCode() |
Serve como função de hash predefinida. (Herdado de Object) |
| GetType() |
Obtém o Type da instância atual. (Herdado de Object) |
| MemberwiseClone() |
Cria uma cópia superficial do atual Object. (Herdado de Object) |
| ToString() |
Devolve uma cadeia que representa o objeto atual. (Herdado de Object) |