Exception handling in C + +

Source: Internet
Author: User
Tags define exception define function throw exception

Throw an exception with throw

Throwing an exception (also known as discarding an exception) is the detection of an exception, which is implemented in C + + with a throw statement and throws an exception if an exception is detected. The format of the statement is:
throw-expression;
If an exception is found in the program segment of the TRY statement block, including the function in which it was called, and the exception is discarded, the exception can be caught and processed by a catch statement after the try statement block, and the condition that is caught and processed is that the type of the thrown exception matches the exception type of the catch statement. Because C + + uses data types to differentiate between different exceptions, the value of the expression in the throw statement has no practical significance when judging the exception, and the type of the expression is particularly important.
"Example 20-2" handles an exception with a divisor of 0. The example uses the Try/catch statement to catch an exception with the above divisor of 0, and throws an exception using the throw statement, thus implementing exception handling, as shown in listing 20-2 of the code.
Code Listing 20-2
1 #include <iostream.h>//Including header files
2 #include <stdlib.h>
3 double fuc (double x, double y)//define function
4 {
5 if (y==0)
6 {
7 Throw y; Divisor is 0, throws an exception
8}
9 return x/y; Otherwise returns two number of quotient
10}
void Main ()
12 {
Double res;
Try//define exception
15 {
RES=FUC (2,3);
cout<< "The result of X/y is:" <<res<<endl;
RES=FUC (4,0); An exception occurred
19}
catch (double)//catch and handle exceptions
21 {
cerr<< "error of dividing zero.\n";
Exit (1); Exception Exit Program
24}
25}
"Run Results" create a new C + + source file in Visual C + +, enter the code above, and run it correctly after compilation.
"Sample parsing" in the preceding code, the try statement is used in the 14th to 19th line of the main function main () to define the exception, which contains 3 statements with possible exceptions, and they are functions that divide the two number of calls. In line 20th to 24th of the code, exception handling is defined, that is, the statement in the code is executed after the exception is caught. Additionally, the code 5~8 line in the function fuc () throws an exception through the throw statement.

Note: In general, throw statements are typically used with try-catch or try-finally statements, and you can use the throw statement to explicitly throw an exception.
////////////

C + + Try_catch

1. Basic Introduction
Try
{
Exception thrown in program
throw value;
}
catch (ValueType V)
{
Exception handler Segment
}
Syntax Summary: Throw throws a value, catch accepts, of course, the throw must be valid in a try statement block.

2, in-depth throw:
(i), after the program accepts the throw statement, the destructor is automatically called, the domain (in parentheses after the try) object is clean, and then the
Into the Catch statement (if you exit the loop in the loop body).

This mechanism can cause some fatal errors, such as when a "class" has a pointer member variable (again a pointer!). ), in the "Class Builder
"The exit caused by the throw statement in" will cause the object pointed to by this pointer not to be refactored. It's very basic and it's not going to go deep.
As shown, you can change the pointer to a class, such as a template class instead of a pointer, and set a destructor inside the template class.

(ii), the statement "throw;" Throws an exception that cannot be caught, even if it is a catch (...) Can not be captured, then enter the termination function
, see catch below.

3. In-depth catch:
The general catch occurs in the form of:
try{}
catch (except1&) {}
catch (except2&) {}
catch (...) {}//Accept all exceptions
Generally written as references (except1&), the reason is simple, efficient.

Question A: What if the exception is thrown, but the catch is not an exception? ( Note that there is no Java-like finally statement )
The default termination function is called when a catch does not catch a matching exception. You can call Set_terminate () to set the terminating function, which is a function pointer with the type: void (*terminate) ().

Here, can be a question: "No try-catch, directly in the program" throw; ”


Some other tricks:
4, try a function body, the form is as follows
void Fun (type1,type2) Try----try placed behind function body
{
function definition
}
catch (Typex) {}
The effect of this usage is equivalent to:
void Fun ()
{
try{function Definition}
}


5, throw a function body, the form is as follows:
void Fun (); Can throw any type of exception
void Fun () throw (EXCEPT1,EXCEPT2,EXCEPT3)
Inside the parentheses is an exception parameter table, this example can only throw in the 3 exception
void Fun () throw ()//Parameter table is empty, cannot throw exception

Question B: What happens if you throw an exception that is not in the "Exception parameter table" in Fun ()?

Answer: Call the terminating function set in Set_terminate (). However, this is only a superficial phenomenon, in effect invoking the default unexpected () function, but this default unexpected () calls the terminating function set in Set_terminate (). The unexpected can be set with set_unexpected (), just like set_terminate (), but after the new "unexpected ()" is set, the terminating function set in Set_terminater is no longer called.

This syntax is very useful, because in the use of other people's code, do not know which place will call what function and throw what exception, with an exception parameter table in the declaration of limitations, very practical.

Exception handling in C + +

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.