Handle exceptions windows forms

Практическое руководство. Обработка ошибок и исключений, происходящих при связывании элементов управления с данными 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:

Unhandled Exception Mode Перечисление

Определение

Определяет, куда приложение Windows Forms должно отправлять необработанные исключения. Defines where a Windows Forms application should send unhandled exceptions.

Направлять все события в обработчик ThreadException, если в файле конфигурации приложения не указано иное. Route all exceptions to the ThreadException handler, unless the application’s configuration file specifies otherwise.

Всегда направлять события в обработчик ThreadException. Always route exceptions to the ThreadException handler. Файл конфигурации приложения не учитывается. Ignore the application configuration file.

Никогда не направлять события в обработчик ThreadException. Never route exceptions to the ThreadException handler. Файл конфигурации приложения не учитывается. Ignore the application configuration file.

Примеры

В следующем примере кода устанавливаются обработчики событий для ошибок, происходящих в Windows Forms потоках и ошибках, происходящих в других потоках. The following code example sets event handlers for both errors that occur on Windows Forms threads and errors that occur on other threads. Он устанавливает SetUnhandledExceptionMode так, чтобы все ошибки обрабатывались приложением, независимо от параметров в файле конфигурации пользователя приложения. It sets SetUnhandledExceptionMode so that all errors are handled by the application, regardless of the settings in the application’s user configuration file. Он использует ThreadException событие для первого события и UnhandledException событие для второго. It uses the ThreadException event for the former, and the UnhandledException event for the latter. Поскольку UnhandledException не может препятствовать завершению работы приложения, в примере просто записывается ошибка в журнал системных событий до завершения. Since UnhandledException cannot prevent an application from terminating, the example simply logs the error in the system Event Log prior to termination.

Читайте также:  Movavi �������� mac os

В этом примере предполагается, что Button в классе определены два элемента управления button1 и button2 Form . This sample assumes that you have defined two Button controls, button1 and button2 , on your Form class.

Комментарии

Это перечисление используется в SetUnhandledExceptionMode . This enumeration is used by SetUnhandledExceptionMode.

В платформа .NET Framework версии 2,0 поведение среды CLR изменилось, чтобы разрешить необработанные исключения для распространения стека вызовов. In the .NET Framework version 2.0, the common language runtime behavior changed to allow unhandled exceptions to propagate up the call stack. Это поведение можно отключить с помощью файла конфигурации приложения. This behavior can be disabled via the application configuration file. См. дополнительные сведения об исключениях в управляемых потоках. For more information, see Exceptions in Managed Threads.

Application. Set Unhandled Exception Mode Метод

Определение

Указывает, как приложение должно реагировать на необработанные исключения. Instructs the application how to respond to unhandled exceptions.

Перегрузки

Указывает, как приложение должно реагировать на необработанные исключения. Instructs the application how to respond to unhandled exceptions.

Предоставляет приложению инструкции, определяющие, как приложение должно отвечать на необработанные исключения, при необходимости применяя поведение, зависящее от потока. Instructs the application how to respond to unhandled exceptions, optionally applying thread-specific behavior.

Примеры

В следующем примере кода задаются обработчики событий для исключений, происходящих в Windows Forms потоках и исключениях, происходящих в других потоках. The following code example sets event handlers for exceptions that occur on Windows Forms threads and exceptions that occur on other threads. Он устанавливает SetUnhandledExceptionMode так, чтобы все исключения обрабатывались приложением, независимо от параметров в файле конфигурации пользователя приложения. It sets SetUnhandledExceptionMode so that all exceptions are handled by the application, regardless of the settings in the application’s user configuration file. Он использует ThreadException событие для обработки исключений потока пользовательского интерфейса, а UnhandledException событие — для обработки исключений потока, не относящегося к ПОЛЬЗОВАТЕЛЬСКОМу интерфейсу. It uses the ThreadException event to handle UI thread exceptions, and the UnhandledException event to handle non-UI thread exceptions. Поскольку UnhandledException не может препятствовать завершению работы приложения, в примере просто записывается ошибка в журнал событий приложения перед завершением работы. Since UnhandledException cannot prevent an application from terminating, the example simply logs the error in the application event log before termination.

В этом примере предполагается, что Button в классе определены два элемента управления button1 и button2 Form . This example assumes that you have defined two Button controls, button1 and button2 , on your Form class.

Читайте также:  Mac os apple download

SetUnhandledExceptionMode(UnhandledExceptionMode)

Указывает, как приложение должно реагировать на необработанные исключения. Instructs the application how to respond to unhandled exceptions.

Параметры

Значение UnhandledExceptionMode, описывающее поведение приложения при выдаче исключения, которое не было перехвачено. An UnhandledExceptionMode value describing how the application should behave if an exception is thrown without being caught.

Исключения

Режим исключения не может быть задан после того, как приложение создало свое первое окно. You cannot set the exception mode after the application has created its first window.

Примеры

В следующем примере кода задаются обработчики событий для исключений, происходящих в Windows Forms потоках и исключениях, происходящих в других потоках. The following code example sets event handlers for exceptions that occur on Windows Forms threads and exceptions that occur on other threads. Он устанавливает SetUnhandledExceptionMode так, чтобы все исключения обрабатывались приложением, независимо от параметров в файле конфигурации пользователя приложения. It sets SetUnhandledExceptionMode so that all exceptions are handled by the application, regardless of the settings in the application’s user configuration file. Он использует ThreadException событие для обработки исключений потока пользовательского интерфейса, а UnhandledException событие — для обработки исключений потока, не относящегося к ПОЛЬЗОВАТЕЛЬСКОМу интерфейсу. It uses the ThreadException event to handle UI thread exceptions, and the UnhandledException event to handle non-UI thread exceptions. Поскольку UnhandledException не может препятствовать завершению работы приложения, в примере просто записывается ошибка в журнал событий приложения перед завершением работы. Since UnhandledException cannot prevent an application from terminating, the example simply logs the error in the application event log before termination.

В этом примере предполагается, что Button в классе определены два элемента управления button1 и button2 Form . This example assumes that you have defined two Button controls, button1 and button2 , on your Form class.

Комментарии

Часто нецелесообразно перехватывать все исключения, вызываемые Windows Forms. It is often not feasible to catch all of the exceptions thrown by Windows Forms. С помощью этого метода можно указать приложению, следует ли перехватывать все необработанные исключения, вызванные Windows Forms компонентами и продолжать работу или предоставлять их пользователю и останавливать выполнение. Using this method, you can instruct your application whether it should catch all unhandled exceptions thrown by Windows Forms components and continue operating, or whether it should expose them to the user and halt execution.

SetUnhandledExceptionModeПеред созданием экземпляра основной формы приложения с помощью метода необходимо вызвать Run метод. Call SetUnhandledExceptionMode before you instantiate the main form of your application using the Run method.

Чтобы перехватить исключения, происходящие в потоках, не созданных и не принадлежащих Windows Forms, используйте UnhandledException обработчик событий. To catch exceptions that occur in threads not created and owned by Windows Forms, use the UnhandledException event handler.

См. также раздел

Применяется к

SetUnhandledExceptionMode(UnhandledExceptionMode, Boolean)

Предоставляет приложению инструкции, определяющие, как приложение должно отвечать на необработанные исключения, при необходимости применяя поведение, зависящее от потока. Instructs the application how to respond to unhandled exceptions, optionally applying thread-specific behavior.

Параметры

Значение UnhandledExceptionMode, описывающее поведение приложения при выдаче исключения, которое не было перехвачено. An UnhandledExceptionMode value describing how the application should behave if an exception is thrown without being caught.

Значение true , чтобы задать режим исключения потока; в противном случае — значение false . true to set the thread exception mode; otherwise, false .

Читайте также:  Windows 10 настроить вход с помощью пин кода

Исключения

Режим исключения не может быть задан после того, как приложение создало свое первое окно. You cannot set the exception mode after the application has created its first window.

Примеры

В следующем примере кода задаются обработчики событий для исключений, происходящих в Windows Forms потоках и исключениях, происходящих в других потоках. The following code example sets event handlers for exceptions that occur on Windows Forms threads and exceptions that occur on other threads. Он устанавливает SetUnhandledExceptionMode так, чтобы все исключения обрабатывались приложением, независимо от параметров в файле конфигурации пользователя приложения. It sets SetUnhandledExceptionMode so that all exceptions are handled by the application, regardless of the settings in the application’s user configuration file. Он использует ThreadException событие для обработки исключений потока пользовательского интерфейса, а UnhandledException событие — для обработки исключений потока, не относящегося к ПОЛЬЗОВАТЕЛЬСКОМу интерфейсу. It uses the ThreadException event to handle UI thread exceptions, and the UnhandledException event to handle non-UI thread exceptions. Поскольку UnhandledException не может препятствовать завершению работы приложения, в примере просто записывается ошибка в журнал событий приложения перед завершением работы. Since UnhandledException cannot prevent an application from terminating, the example simply logs the error in the application event log before termination.

В этом примере предполагается, что Button в классе определены два элемента управления button1 и button2 Form . This example assumes that you have defined two Button controls, button1 and button2 , on your Form class.

Комментарии

Часто нецелесообразно перехватывать все исключения, вызываемые Windows Forms. It is often not feasible to catch all of the exceptions thrown by Windows Forms. С помощью этого метода можно указать приложению, следует ли перехватывать все необработанные исключения, вызванные Windows Forms компонентами и продолжать работу или предоставлять их пользователю и останавливать выполнение. Using this method, you can instruct your application whether it should catch all unhandled exceptions thrown by Windows Forms components and continue operating, or whether it should expose them to the user and halt execution.

SetUnhandledExceptionModeПеред созданием экземпляра основной формы приложения с помощью метода необходимо вызвать Run метод. Call SetUnhandledExceptionMode before you instantiate the main form of your application using the Run method.

Если threadScope параметр имеет значение true , то устанавливается режим исключения потока. When threadScope is true , the thread exception mode is set. Режим исключения потока переопределяет режим исключения приложения, если mode не задано значение Automatic . The thread exception mode overrides the application exception mode if mode is not set to Automatic.

Если threadScope параметр имеет значение false , то устанавливается режим исключения приложения. When threadScope is false , the application exception mode is set. Режим исключений приложения используется для всех потоков, имеющих Automatic режим. The application exception mode is used for all threads that have the Automatic mode. Установка режима исключения приложения не влияет на настройку текущего потока. Setting the application exception mode does not affect the setting of the current thread.

Чтобы перехватить исключения, происходящие в потоках, не созданных и не принадлежащих Windows Forms, используйте UnhandledException обработчик событий. To catch exceptions that occur in threads not created and owned by Windows Forms, use the UnhandledException event handler.

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