How to catch all exceptions c
How to catch all exceptions c
Catch exceptions in Visual C++
This article describes how to use a try-catch-finally block to catch an exception.
Original product version: В Visual C++
Original KB number: В 815662
Summary
A try-catch-finally block is a wrapper that you put around any code where an exception might occur. Catching and dealing with exceptions are standard programming tasks.
A try-catch-finally block is made up of the following sections:
On the File menu, point to New, and then click Project.
In Visual C++, click Visual C++ under Project Types, and then click CLR Console Application under Templates.
In the Name box, type Q815662, and then click OK.
Replace all the code in the Q815662.cpp code window with the following code. The code declares and initializes three variables. The initialization of k causes an error.
Press F5. You receive a System.DivideByZeroException exception.
Wrap a try-catch statement around your code to capture the error. The following code catches all errors that are thrown in the code and displays a generic error message. Replace the code in the Q815662.cpp code window with the following code:
Press CTRL+F5 to run the application.
The error message from the catch block is displayed instead of the system exception error message.
If you must do clean up or post-processing regardless of an error, use the __finally part of the try-catch-finally statement. The code in the finally part of the statement is always executed, regardless of an exception. The following code displays the following message in the console, even if no error occurred:
Replace the code in the Q815662.cpp code window with the following code:
Press CTRL+F5 to run the project.
You can use the exception object with the catch statement to retrieve details about the exception. An exception object has a number of properties that can help you to identify the source, and has stack information about an exception. This information can be useful to help track down the original cause of the exception, or can provide a better explanation of its source. The following sample catches an exception and gives a specific error message. Replace the code in the Q815662.cpp code window with the following code:
Until this point, you’ve dealt with a non-specific exception. However, if you know in advance what kind of exception is going to occur, you can catch the expected exception, and process it accordingly. Use the multiple catch blocks that are described in the following code to catch all other exceptions and deal with them:
Because computer configurations may be different, the sample in this step may or may not throw an exception. If you want to force an input/output (IO) exception, change the file path to a folder that doesn’t exist on your computer.
try-catch (C# Reference)
The try-catch statement consists of a try block followed by one or more catch clauses, which specify handlers for different exceptions.
When an exception is thrown, the common language runtime (CLR) looks for the catch statement that handles this exception. If the currently executing method does not contain such a catch block, the CLR looks at the method that called the current method, and so on up the call stack. If no catch block is found, then the CLR displays an unhandled exception message to the user and stops execution of the program.
The try block contains the guarded code that may cause the exception. The block is executed until an exception is thrown or it is completed successfully. For example, the following attempt to cast a null object raises the NullReferenceException exception:
Although the catch clause can be used without arguments to catch any type of exception, this usage is not recommended. In general, you should only catch those exceptions that you know how to recover from. Therefore, you should always specify an object argument derived from System.Exception. The exception type should be as specific as possible in order to avoid incorrectly accepting exceptions that your exception handler is actually not able to resolve. As such, prefer concrete exceptions over the base Exception type. For example:
It is possible to use more than one specific catch clause in the same try-catch statement. In this case, the order of the catch clauses is important because the catch clauses are examined in order. Catch the more specific exceptions before the less specific ones. The compiler produces an error if you order your catch blocks so that a later block can never be reached.
Using catch arguments is one way to filter for the exceptions you want to handle. You can also use an exception filter that further examines the exception to decide whether to handle it. If the exception filter returns false, then the search for a handler continues.
Exception filters are preferable to catching and rethrowing (explained below) because filters leave the stack unharmed. If a later handler dumps the stack, you can see where the exception originally came from, rather than just the last place it was rethrown. A common use of exception filter expressions is logging. You can create a filter that always returns false that also outputs to a log, you can log exceptions as they go by without having to handle them and rethrow.
A throw statement can be used in a catch block to re-throw the exception that is caught by the catch statement. The following example extracts source information from an IOException exception, and then throws the exception to the parent method.
You can catch one exception and throw a different exception. When you do this, specify the exception that you caught as the inner exception, as shown in the following example.
You can also re-throw an exception when a specified condition is true, as shown in the following example.
From inside a try block, initialize only variables that are declared therein. Otherwise, an exception can occur before the execution of the block is completed. For example, in the following code example, the variable n is initialized inside the try block. An attempt to use this variable outside the try block in the Write(n) statement will generate a compiler error.
For more information about catch, see try-catch-finally.
Exceptions in async methods
When control reaches an await in the async method, progress in the method is suspended until the awaited task completes. When the task is complete, execution can resume in the method. For more information, see Asynchronous programming with async and await.
To catch the exception, await the task in a try block, and catch the exception in the associated catch block. For an example, see the Async method example section.
A task can be in a faulted state because multiple exceptions occurred in the awaited async method. For example, the task might be the result of a call to Task.WhenAll. When you await such a task, only one of the exceptions is caught, and you can’t predict which exception will be caught. For an example, see the Task.WhenAll example section.
Example
Two catch blocks example
In the following example, two catch blocks are used, and the most specific exception, which comes first, is caught.
Async method example
The following example illustrates exception handling for async methods. To catch an exception that an async task throws, place the await expression in a try block, and catch the exception in a catch block.
Task.WhenAll example
The following example illustrates exception handling where multiple tasks can result in multiple exceptions. The try block awaits the task that’s returned by a call to Task.WhenAll. The task is complete when the three tasks to which WhenAll is applied are complete.
Each of the three tasks causes an exception. The catch block iterates through the exceptions, which are found in the Exception.InnerExceptions property of the task that was returned by Task.WhenAll.
C# language specification
For more information, see The try statement section of the C# language specification.
Обработка исключений
При выполнении программы может возникнуть ряд ненормальных условий и ошибок, называемых исключениями. К ним могут относиться нехватки памяти, ошибки выделения ресурсов и невозможность поиска файлов.
Библиотека Microsoft Foundation Class использует схему обработки исключений, которая моделируется в тесном соответствии с предложенным Комитетом по стандартам ANSI для C++. Перед вызовом функции, которая может столкнуться с аномальной ситуацией, необходимо настроить обработчик исключений. Если функция обнаруживает аномальное состояние, она вызывает исключение, и управление передается обработчику исключений.
Несколько макросов, входящих в библиотека Microsoft Foundation Class, настроили обработчики исключений. Ряд других глобальных функций помогает создавать специализированные исключения и завершать программы при необходимости. Эти макросы и глобальные функции делятся на следующие категории:
Макросы исключений, которые представляют собой структуру обработчика исключений.
Функции, создающие исключения), которые создают исключения конкретных типов.
Функции завершения, которые вызывают завершение программы.
Примеры и дополнительные сведения см. в статье исключения.
Макросы исключений
Функции Exception-Throwing
Имя | Описание |
---|---|
AfxThrowArchiveException | Создает исключение архива. |
AfxThrowFileException | Вызывает исключение файла. |
AfxThrowInvalidArgException | Вызывает исключение недопустимого аргумента. |
AfxThrowMemoryException | Вызывает исключение памяти. |
AfxThrowNotSupportedException | Вызывает исключение «не поддерживается». |
AfxThrowResourceException | вызывает исключение Windows ресурс — не найдено. |
AfxThrowUserException | Создает исключение в действии, инициированном пользователем. |
MFC предоставляет две функции генерации исключений, специально предназначенные для исключений OLE:
Функции исключений OLE
Имя | Описание |
---|---|
AfxThrowOleDispatchException | Создает исключение в функции OLE Automation. |
AfxThrowOleException | Вызывает исключение OLE. |
Для поддержки исключений баз данных классы баз данных предоставляют два класса исключений, CDBException и CDaoException и глобальные функции для поддержки типов исключений:
Функции исключений DAO
Имя | Описание |
---|---|
афкссровдаоексцептион | Создает исключение кдаоексцептион из собственного кода. |
AfxThrowDBException | Создает исключение кдбексцептион из собственного кода. |
MFC предоставляет следующую функцию завершения:
Функции завершения
Имя | Описание |
---|---|
AfxAbort | Вызывается для завершения работы приложения при возникновении неустранимой ошибки. |
Комментарии
Дополнительные сведения см. в статье исключения.
Пример
Требования
CATCH
Параметры
exception_class
Указывает тип исключения для проверки. Список стандартных классов исключений см. в разделе Class CException.
exception_object_pointer_name
Задает имя для указателя на объект Exception, который будет создан с помощью макроса. Для доступа к объекту исключения в блоке catch можно использовать имя указателя. Эта переменная объявлена для вас.
Комментарии
Код обработки исключений может опрашивать объект исключения, если это уместно, чтобы получить дополнительные сведения о конкретной причине исключения. Вызов макроса THROW_LAST для сдвига обработки на следующий внешний кадр исключения. Завершите блок try с помощью макроса END_CATCH.
Указатель объекта исключения создается с помощью макроса. Вам не нужно объявлять его самостоятельно.
Блок catch определяется как область C++, разделенная фигурными скобками. Если объявить переменные в этой области, они будут доступны только в пределах этой области. Это также относится к exception_object_pointer_name.
Дополнительные сведения об исключениях и макросе CATCH см. в статье исключения.
Пример
CATCH_ALL
Параметры
exception_object_pointer_name
Задает имя для указателя на объект Exception, который будет создан с помощью макроса. Для доступа к объекту исключения в CATCH_ALL блоке можно использовать имя указателя. Эта переменная объявлена для вас.
Комментарии
Код обработки исключений может опрашивать объект исключения, если это уместно, чтобы получить дополнительные сведения о конкретной причине исключения. THROW_LAST Вызов макроса для сдвига обработки на следующий внешний кадр исключения. Если вы используете CATCH_ALL, завершите блок try с помощью макроса END_CATCH_ALL.
Блок CATCH_ALL определяется как область C++, разделенная фигурными скобками. Если объявить переменные в этой области, они будут доступны только в пределах этой области.
Дополнительные сведения об исключениях см. в статье исключения.
Пример
Требования
Заголовок AFX. h
AND_CATCH
Параметры
exception_class
Указывает тип исключения для проверки. Список стандартных классов исключений см. в разделе Class CException.
exception_object_pointer_name
Имя для указателя на объект Exception, который будет создан с помощью макроса. Для доступа к объекту исключения в блоке AND_CATCH можно использовать имя указателя. Эта переменная объявлена для вас.
Комментарии
Используйте макрос CATCH для перехвата одного типа исключения, а затем макрос AND_CATCH для перехвата каждого последующего типа. Завершите блок try с помощью макроса END_CATCH.
Пример
Требования
Заголовок AFX. h
AND_CATCH_ALL
Параметры
exception_object_pointer_name
Имя для указателя на объект Exception, который будет создан с помощью макроса. Для доступа к объекту исключения в блоке AND_CATCH_ALL можно использовать имя указателя. Эта переменная объявлена для вас.
Комментарии
Используйте макрос catch для перехвата одного типа исключения, а затем макрос AND_CATCH_ALL для перехвата всех остальных последующих типов. Если вы используете AND_CATCH_ALL, завершите блок try с помощью макроса END_CATCH_ALL.
Блок AND_CATCH_ALL определяется как область C++ (разделенная фигурными скобками). При объявлении переменных в этой области Помните, что они доступны только в пределах этой области.
Требования
Заголовок AFX. h
END_CATCH
Комментарии
Дополнительные сведения о макросе END_CATCH см. в статье исключения.
Требования
Заголовок AFX. h
END_CATCH_ALL
Помечает конец последнего CATCH_ALL88 или AND_CATCH_ALL блока.
Требования
Заголовок AFX. h
THROW (MFC)
Создает указанное исключение.
Параметры
Комментарии
Вызовет прерывание выполнения программы и передает управление соответствующему блоку catch в программе. Если блок catch не указан, то управление передается модулю Библиотека Microsoft Foundation Class, который выводит сообщение об ошибке и завершает работу.
Дополнительные сведения см. в статье исключения.
Требования
Заголовок AFX. h
THROW_LAST
Комментарии
Дополнительные сведения см. в статье исключения.
Пример
Требования
Заголовок AFX. h
AfxThrowArchiveException
Создает исключение архива.
Параметры
cause
Задает целое число, указывающее причину исключения. Список возможных значений см. в разделе карчивиксцептион:: m_cause.
лпсзарчивенаме
Указывает на строку, содержащую имя CArchive объекта, вызвавшего исключение (если доступно).
Требования
Заголовок AFX. h
AfxThrowFileException
Вызывает исключение файла.
Параметры
cause
Задает целое число, указывающее причину исключения. Список возможных значений см. в разделе кфиликсцептион:: m_cause.
лосеррор
Содержит номер ошибки операционной системы (при наличии), который указывает причину исключения. Список кодов ошибок см. в руководстве по операционной системе.
лпсзфиленаме
Указывает на строку, содержащую имя файла, вызвавшего исключение (если доступно).
Комментарии
Вы несете ответственность за определение причины на основе кода ошибки операционной системы.
Требования
Заголовок AFX. h
AfxThrowInvalidArgException
Вызывает исключение недопустимого аргумента.
Синтаксис
Примечания
Эта функция вызывается, когда используются недопустимые аргументы.
Требования
Заголовок: AFX. h
AfxThrowMemoryException
Вызывает исключение памяти.
Комментарии
Требования
Заголовок AFX. h
AfxThrowNotSupportedException
Создает исключение, которое является результатом запроса неподдерживаемой функции.
Требования
Заголовок AFX. h
AfxThrowResourceException
Вызывает исключение ресурса.
Комментарии
эта функция обычно вызывается, когда не удается загрузить Windows ресурс.
Требования
Заголовок AFX. h
AfxThrowUserException
Создает исключение для завершения операции пользователя.
Комментарии
Эта функция обычно вызывается сразу после того, как AfxMessageBox пользователь сообщил об ошибке.
Требования
Заголовок AFX. h
AfxThrowOleDispatchException
Эта функция используется для создания исключения в функции OLE Automation.
Параметры
wCode
Код ошибки, относящийся к вашему приложению.
лпсздескриптион
Описание ошибки текстовом.
ндескриптионид
Идентификатор ресурса для описания ошибки текстовом.
нхелпид
Контекст справки для справки вашего приложения (. Файл HLP).
Комментарии
сведения, предоставленные этой функции, могут отображаться в приложении, управляющем приложением (Microsoft Visual Basic или другом клиентском приложении OLE-автоматизации).
Пример
Требования
Заголовок AFX. h
AfxThrowOleException
Создает объект типа COleException и создает исключение.
Параметры
SC
Код состояния OLE, указывающий причину исключения.
ч
Обрабатывает код результата, указывающий причину исключения.
Комментарии
Версия, принимающая HRESULT в качестве аргумента, преобразует этот код результата в соответствующий SCODE. дополнительные сведения о HRESULT и SCODE см. в разделе структура кодов ошибок COM в Windows SDK.
Требования
Заголовок афксдао. h
AfxThrowDaoException
Вызовите эту функцию, чтобы вызвать исключение типа кдаоексцептион из собственного кода.
Параметры
нафксдаоеррор
Целочисленное значение, представляющее расширенный код ошибки DAO, который может быть одним из значений, перечисленных в разделе кдаоексцептион:: m_nAfxDaoError.
SCODE
Код ошибки OLE из DAO типа SCODE. Дополнительные сведения см. в разделе кдаоексцептион:: m_scode.
Комментарии
Сведения об исключениях, связанных с классами MFC DAO, см. в разделе класс CDaoException в этой книге, а в статье исключения: исключения базы данных.
Требования
Заголовок афксдб. h
AfxThrowDBException
Вызовите эту функцию, чтобы создать исключение типа CDBException из собственного кода.
Параметры
нреткоде
Значение типа РЕТКОДЕ, определяющее тип ошибки, вызвавшей исключение.
файле
Указатель на CDatabase объект, представляющий соединение с источником данных, с которым связано исключение.
hstmt
Обработчик ODBC ХСТМТ, указывающий маркер инструкции, с которым связано исключение.
Комментарии
Платформа вызывается AfxThrowDBException при получении РЕТКОДЕ ODBC из вызова функции API ODBC и ИНТЕРПРЕТИРУЕТ реткоде как исключительную ситуацию, а не как предполагаемую ошибку. Например, операция доступа к данным может завершиться ошибкой из-за ошибки чтения с диска.
сведения о значениях реткоде, определенных ODBC, см. в главе 8 «получение сведений о состоянии и ошибках» в Windows SDK. Дополнительные сведения о расширениях MFC для этих кодов см. в разделе Class кдбексцептион.
Требования
Заголовок AFX. h
AfxAbort
Функция завершения по умолчанию, предоставляемая MFC.
Комментарии
AfxAbort вызывается внутренне функциями-членами MFC при возникновении неустранимой ошибки, например неперехваченного исключения, которое не может быть обработано. Можно вызвать AfxAbort в редких случаях, когда возникает фатальная ошибка, из-за которой невозможно выполнить восстановление.
Exceptions: Catching and Deleting Exceptions
Your exception handlers must delete exception objects they handle, because failure to delete the exception causes a memory leak whenever that code catches an exception.
Your catch block must delete an exception when:
The catch block throws a new exception.
Of course, you must not delete the exception if you throw the same exception again:
Execution returns from within the catch block.
To catch and delete exceptions
Use the try keyword to set up a try block. Execute any program statements that might throw an exception within a try block.
Use the catch keyword to set up a catch block. Place exception-handling code in a catch block. The code in the catch block is executed only if the code within the try block throws an exception of the type specified in the catch statement.
The following skeleton shows how try and catch blocks are normally arranged:
When an exception is thrown, control passes to the first catch block whose exception-declaration matches the type of the exception. You can selectively handle different types of exceptions with sequential catch blocks as listed below:
try, throw, and catch Statements (C++)
First, use a try block to enclose one or more statements that might throw an exception.
To handle exceptions that may be thrown, implement one or more catch blocks immediately following a try block. Each catch block specifies the type of exception it can handle.
Example
Remarks
The code after the try clause is the guarded section of code. The throw expression throws—that is, raises—an exception. The code block after the catch clause is the exception handler. This is the handler that catches the exception that’s thrown if the types in the throw and catch expressions are compatible. For a list of rules that govern type-matching in catch blocks, see How Catch Blocks are Evaluated. If the catch statement specifies an ellipsis (. ) instead of a type, the catch block handles every type of exception. When you compile with the /EHa option, these can include C structured exceptions and system-generated or application-generated asynchronous exceptions such as memory protection, divide-by-zero, and floating-point violations. Because catch blocks are processed in program order to find a matching type, an ellipsis handler must be the last handler for the associated try block. Use catch(. ) with caution; do not allow a program to continue unless the catch block knows how to handle the specific exception that is caught. Typically, a catch(. ) block is used to log errors and perform special cleanup before program execution is stopped.
A throw expression that has no operand re-throws the exception currently being handled. We recommend this form when re-throwing the exception, because this preserves the original exception’s polymorphic type information. Such an expression should only be used in a catch handler or in a function that’s called from a catch handler. The re-thrown exception object is the original exception object, not a copy.
Источники информации:
- http://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/try-catch
- http://docs.microsoft.com/ru-ru/cpp/mfc/reference/exception-processing?view=msvc-160
- http://docs.microsoft.com/en-us/cpp/mfc/exceptions-catching-and-deleting-exceptions?view=msvc-140
- http://docs.microsoft.com/en-us/cpp/cpp/try-throw-and-catch-statements-cpp?view=msvc-170