Windows form exception handling

Практическое руководство. Обработка ошибок и исключений, происходящих при связывании элементов управления с данными How to: Handle Errors and Exceptions that Occur with Databinding

Зачастую при привязке базовых бизнес-объектов к элементам управления возникают ошибки и исключения. Oftentimes exceptions and errors occur on the underlying business objects when you bind them to controls. Эти ошибки и исключения можно перехватывать, а затем исправлять или передавать сведения об ошибке пользователю путем обработки события BindingComplete для конкретного компонента Binding, BindingSource или CurrencyManager. You can intercept these errors and exceptions and then either recover or pass the error information to the user by handling the BindingComplete event for a particular Binding, BindingSource, or CurrencyManager component.

Пример Example

В данном примере кода показан способ обработки ошибок и исключений, возникающих при выполнении операции привязки данных. This code example demonstrates how to handle errors and exceptions that occur during a data-binding operation. Он демонстрирует перехват ошибок путем обработки события Binding.BindingComplete объектов Binding. It demonstrates how to intercept errors by handling the Binding.BindingComplete event of the Binding objects. Для перехвата ошибок и исключений с помощью обработки этого события необходимо включить поддержку форматирования для привязки. In order to intercept errors and exceptions by handling this event, you must enable formatting for the binding. Форматирование можно включить при создании привязки или добавлении в коллекцию привязок, или установив значение свойства FormattingEnabled равным true . You can enable formatting when the binding is constructed or added to the binding collection, or by setting the FormattingEnabled property to true .

Во время выполнения, если введена пустая строка в качестве имени или значение меньше 100 в качестве числа, то появится окно с сообщением. When the code is running and an empty string is entered for the part name or a value less than 100 is entered for the part number, a message box appears. Это происходит в результате обработки события Binding.BindingComplete для привязок этих текстовых полей. This is a result of handling the Binding.BindingComplete event for these textbox bindings.

Компиляция кода Compiling the Code

Для этого примера требуются: This example requires:

Top-level Exception Handling in Windows Forms Applications – Code Listing 1

This is a very basic code example of how to use the ThreadException event to handle exceptions occurring anywhere on the main GUI thread in a Windows Forms application. My blog article ‘Top-level Exception Handling in Windows Forms Applications’ discusses this in more detail.

From looking at the forums it seems many people have problems getting the ThreadException event to fire correctly. To make sure you can get my example working I have included quite detailed instructions: you probably don’t need these though!

Читайте также:  Горячие клавиши windows 10 печать документа

1. Create a new C# Windows Application in Visual Studio 2005, calling it ExceptionHandling1.

2. Replace the code in Program.cs with the code below.

using System . Windows . Forms ;

using System . Threading ;

static class Program

/// The main entry point for the application.

static void
Main ()

Application . ThreadException += new ThreadExceptionEventHandler ( new ThreadExceptionHandler (). ApplicationThreadException );

Application . Run ( new Form1 ());

/// Handles any thread exceptions

public class ThreadExceptionHandler

public void ApplicationThreadException ( object sender , ThreadExceptionEventArgs e )

MessageBox . Show ( e . Exception . Message , “An exception occurred:” , MessageBoxButtons . OK , MessageBoxIcon . Error );

3. Replace the code behind the default Form1 with the code below (Form1.cs):

using System . Windows . Forms ;

using System . Threading ;

public partial class Form1 : Form

private void throwExceptionButton_Click ( object sender , EventArgs e )

private void ThrowException ()

// Note that in general you shouldn’t throw a generic ApplicationException

// but should use a more specific exception class derived from it

throw new ApplicationException ( “Monkey exception” );

private void exceptionOnNewFormButton_Click ( object sender , EventArgs e )

Form1 form = new Form1 ();

4. Replace the code in Form1.Designer.cs with the code below:

partial class Form1

/// Required designer variable.

private System . ComponentModel . IContainer components = null ;

/// Clean up any resources being used.

true if managed resources should be disposed; otherwise, false.

protected override void Dispose ( bool disposing )

if ( disposing && ( components != null ))

base . Dispose ( disposing );

#region Windows Form Designer generated code

/// Required method for Designer support – do not modify

/// the contents of this method with the code editor.

private void InitializeComponent ()

this . throwExceptionButton = new System . Windows . Forms . Button ();

this . newFormButton = new System . Windows . Forms . Button ();

this . throwExceptionButton . Location = new System . Drawing . Point (12, 12);

this . throwExceptionButton . Name = “throwExceptionButton” ;

this . throwExceptionButton . Size = new System . Drawing . Size (75, 51);

this . throwExceptionButton . TabIndex = 0;

this . throwExceptionButton . Text = “Throw Exception” ;

this . throwExceptionButton . UseVisualStyleBackColor = true ;

this . throwExceptionButton . Click += new System . EventHandler ( this . throwExceptionButton_Click );

this . newFormButton . Location = new System . Drawing . Point (93, 12);

this . newFormButton . Name = “newFormButton” ;

this . newFormButton . Size = new System . Drawing . Size (75, 51);

this . newFormButton . TabIndex = 2;

this . newFormButton . Text = “New Form” ;

this . newFormButton . UseVisualStyleBackColor = true ;

this . newFormButton . Click += new System . EventHandler ( this . exceptionOnNewFormButton_Click );

this . AutoScaleDimensions = new System . Drawing . SizeF (6F, 13F);

this . AutoScaleMode = System . Windows . Forms . AutoScaleMode . Font ;

this . ClientSize = new System . Drawing . Size (202, 79);

this . Controls . Add ( this . newFormButton );

this . Controls . Add ( this . throwExceptionButton );

this . Name = “ExceptionHandlingForm” ;

this . Text = “Exception Handling” ;

this . ResumeLayout ( false );

private System . Windows . Forms . Button throwExceptionButton ;

private System . Windows . Forms . Button newFormButton ;

5. Run this code. If you run the code in debug, when you hit the ‘Throw Exception’ button the code will break saying that an exception has occurred (unless you’ve disabled this). If you now hit F5 to continue you will see that the top-level exception handler is being called. If you run the code by double-clicking ExceptionHandling1.exe you will see that the top-level exception handler has been called directly.

Читайте также:  Linux vim удалить строку

Global Exception Handling for winforms control

When working on ASP.NET 1.1 projects I always used the Global.asax to catch all errors. I’m looking for a similar way to catch all exceptions in a Windows Forms user control, which ends up being a hosted IE control. What is the proper way to go about doing something like this?

5 Answers 5

You need to handle the System.Windows.Forms.Application.ThreadException event for Windows Forms. This article really helped me: http://bytes.com/forum/thread236199.html.

Currently in my winforms app I have handlers for Application.ThreadException , as above, but also AppDomain.CurrentDomain.UnhandledException

Most exceptions arrive via the ThreadException handler, but the AppDomain one has also caught a few in my experience

If you’re using VB.NET, you can tap into the very convenient ApplicationEvents.vb. This file comes for free with a VB.NET WinForms project and contains a method for handling unhandled exceptions.

To get to this nifty file, it’s «Project Properties >> Application >> Application Events»

If you’re not using VB.NET, then yeah, it’s handling Application.ThreadException.

To Handle Exceptions Globally.

Windows Application

Generally Used in Main Method. Refer MSDN Thread Exception

Asp.Net

Console Application

Generally used in Main Method. Refer MSDN UnhandledException

Catch Application Exceptions in a Windows Forms Application

Is there anyway to catch expections that is thrown by anywhere in the code? I would like to catch exceptions and handle them in a similar manner rather than writing try catch blocks for each functionality.

4 Answers 4

In Windows Forms applications, when an exception is thrown anywhere in the application (on the main thread or during asynchronous calls), you can catch it by registering for the ThreadException event on the Application. In this way you can treat all the exceptions in the same way.

I think this is a close as you can get to what you are looking for within a win form application.

Without doing all of these steps you run the risk of having some exceptions get unhandled.

The obvious answer is to put an exception handler at the top of your execution chain.

This will catch any exception that occurs on your main GUI thread. If you also want to globally catch exceptions that occur on all threads you can subscribe to the AppDomain.UnhandledException event and handle there.

Now on to the advice .

These options should only be used as a last resort, say, if you want to suppress accidentally uncaught exceptions from presentation to the user. You should be catching sooner whenever possible, when you know somthing about the context of the exception. Even better, you may be able to do something about the problem.

Structured exception handling might seem like an unecessary overhead which you can work around with a catch all but, it exists because this is not the case. What is more, this work should be done as the code is written, when the developer has the logic fresh in thier mind. Do not be lazy and leave this work for later or for some more profressional developer to pick up.

Читайте также:  Проигрыватель lossless для windows

Winforms issue — Error creating window handle [duplicate]

We are seeing this error in a Winform application. Can anyone help on why you would see this error, and more importantly how to fix it or avoid it from happening.

10 Answers 10

Have you run Process Explorer or the Windows Task Manager to look at the GDI Objects, Handles, Threads and USER objects? If not, select those columns to be viewed (Task Manager choose View->Select Columns. Then run your app and take a look at those columns for that app and see if one of those is growing really large.

It might be that you’ve got UI components that you think are cleaned up but haven’t been Disposed.

Here’s a link about this that might be helpful.

The windows handle limit for your application is 10,000 handles. You’re getting the error because your program is creating too many handles. You’ll need to find the memory leak. As other users have suggested, use a Memory Profiler. I use the .Net Memory Profiler as well. Also, make sure you’re calling the dispose method on controls if you’re removing them from a form before the form closes (otherwise the controls won’t dispose). You’ll also have to make sure that there are no events registered with the control. I myself have the same issue, and despite what I already know, I still have some memory leaks that continue to elude me..

See this post of mine about «Error creating window handle» and how it relates to USER Objects and the Desktop Heap. I provide some solutions.

This problem is almost always related to the GDI Object count, User Object count or Handle count and usually not because of an out-of-memory condition on your machine.

When I am tracking one of these bugs, I open ProcessExplorer and watch these columns: Handles, Threads, GDI Objects, USER Objects, Private Bytes, Virtual Size and Working Set.

(In my experience, the problem is usually an object leak due to an event handler holding the object and preventing it from being disposed.)

Well, in my case it was definitely the USER Objects that were out of control. I looked in the Windows Task Manager and sure enough, the USER Objects count was at 10’000 exactly.

I am dynamically embedding property and list sheets in Tab Pages by setting the Parent property of the property or list sheet’s container panel to that of the Tab Page. I am conditionally recycling or re-creating the property and list sheet forms depending on the type of collection being listed or class type of the object being inspected.

NB: In Delphi, all controls had an Owner and a Parent property. Even if one changed the Parent property of a control, it would still be disposed by its owner when the owning control got destroyed.

Оцените статью