Exceptions are problems that may arise during the execution of a program, and C + + exceptions are special cases that occur when a program is run, such as an attempt to divide by 0. Exceptions provide a way to transfer program control, with C + + exception handling designed to three keywords:try, catch, throw.
- Throw: When the problem occurs, the program throws an exception. This is done by using the throw keyword. Throw back if an lvalue
- catch: The exception is caught by the exception handler where you want to handle the problem. The catch keyword is used to catch exceptions.
- Try: The code in the try block identifies the specific exception that will be activated. It is usually followed by one or more catch blocks.
If a block throws an exception, the method that catches the exception uses theTryAndCatchKey word. Code in a try block that might throw an exception, the code in the try block is called the protection Code. The syntax for using the Try/catch statement is as follows:
Try { //Protection Code//Protection code may throw the following three types of exceptions, the exception type can be class type and default data type }catch (ExceptionType1 E1) { //Catch block }catch (ExceptionType1 E2) { //Catch block }catch (ExceptionType1 EN) { //Catch block } |
throwing exceptions and catching exceptions The
throw statement throws an exception anywhere in the code block. The operand of the throw statement can be an arbitrary expression, and the type of the result of the expression determines the type of exception that is thrown. The
catch block follows the
try block and is used to catch the exception. You can specify the type of exception you want to catch, which is determined by the exception declaration in parentheses after the catch keyword.
#include <iostream> using namespace std; Double Division (int a,int b) { if (0==b) //divisor is 0, throws an exception { throw "divisor cannot be 0"; //exception type is const char * } return a/b; } int main () { int a = 4, b = 0; int res; try { //Protection Code res = Division (a,0); } Catch(const char* msg) { cout<<msg<<endl; } catch(...) {cout<< "abnormal generation" <<endl; } cout<< "res =" <<res<<endl; return 0; } |
The value of the expression following the throw is picked up by the corresponding catch
catch (...)//indicates that any type of exception can be accepted.
|
C + + Exceptions