In C ++ exception mechanism Detailed

  Two days found that some concepts do not understand, exception class, capturing the flow of execution and other anomalies, and decided to review the exception mechanism C ++ inside, by analogy in learning Java, learning Java's exception mechanism of it, there is the C ++ based learning Java the syntax is very easy to understand, too, learning Java will have a deeper understanding of object-oriented C ++, Java, after all, everything is kind, said the following topic. In C ++ exception mechanism, I look at the previous C ++ learning videos, Northwestern Polytechnical University - C ++ programming , speaker teachers Wei Ying, personally feel very good a C ++ learning course, very systematic, progressive, good to see again guaranteed to learn something, that is the kind of feel after reading Oh, speak very good feeling, to review the inspection course, you'll have problems.

First, the basic concept of exception handling

1, the concept of exceptions

Refers to the abnormal appearance of the program is running is not normal. The following anomalies may occur during program execution:

  • CPU error, for example in the calculation process, division by zero occurs
  • Memory exception:
    using the new application or malloc dynamic memory but not enough storage space;
    array subscript bounds;
    use of wild pointers, dangling pointer memory read
  • Equipment malfunction:
    Can not open file, or open a file, but the file can be damaged, so that the data can not be read;
    move file or disk file when the disk is being read;
    are in the printer is turned off but the device;
    network disconnection being used or clog
  • User data exception:
    Scanf input data format error or error type
    database error being processed
    program data is assumed environment changes

2. The method of exception handling

  • Model terminate
    in termination model, assuming that the error is critical that the program can not return to where the exception was to continue. Once an exception is thrown, it means that an error has been irretrievably lost, the program can not continue.
  • Recovery model
    recovery model refers to the work of the exception handler is correct the error, and then retry the process to mobilize the problem.

3, exception handling mechanism

  Throws an exception ( throw), abnormalities ( try), catch the exception ( catch)

  Rationale: The program needs to be detected in the try block, the exception handling program into the catch block. An exception occurred while performing a function, the function may not be processed immediately, but throws an exception message and passes it on to call function level, on a function to capture this information during processing. If the process is not a function, it is passed up step by step, if delivered to the highest level (main function) is not treated, ultimately, abnormal termination of program execution.

  C ++ mechanism for exception handling to make an exception and treatment can help to accomplish the same function, the advantage of this is that the deep-seated function to focus on problem solving, rather than undertake the task of handling exceptions, reducing the burden of deep-level functions, and the focus on the task exception handling to a certain level functions dedicated to resolve.

Second, the realization exception handling

1, an exception is thrown

  Can throw 表达式throw an exception, the exception thrown to the calling function to handle, generally abnormal manner similar argument to the function throw (the throw a) and (by the catch) type capture, the throw determines the parabolic expression the type of anomaly. Since C ++ is based on the type to differentiate abnormal, so when an exception is thrown, throw expression refers to no practical significance, and the type of expression is very important. If the program has many to throw an exception, should be distinguished from each other with different types of expressions.

if (test == 0) throw test;	//抛出 int 型异常
if (test == 1) throw 'a';	//抛出 char 型异常
if (test == 2) throw 333.23;//抛出 double 型异常

  The description of the throw

  • When executed throw, the throw does not perform behind the statement, but the program is transferred from a throw to match the catch, the catch may be in the same function catch, abnormal function can also occur on a direct or indirect call in level function.
  • A thrown object is initialized with throw expression "exception object", will be passed to the exception object corresponding to the catch, and after handling the exception is completed canceled, so must the exception object types can be replicated (with the copy constructor) .
  • If the array is thrown, the object is automatically converted to the thrown point to the first element of the array pointer is thrown if a function, the function is converted into a pointer to the function.
  • If you throw a pointer that is a pointer to the derived class to a base class object, then the object is divided, only the portion of the base class is thrown.
  • Throw pointing to a local object pointer to make mistakes, because when thrown pointers, you must make sure to enter the exception handler pointer points to an object still exists.

2, detection of the captured abnormal

Detection is generally in the form of catch exceptions:

try
{
	...		//检测程序块(可能抛出异常的代码)
}
catch(异常说明符 1)
{
	...		//处理程序(当异常说明符 1 被抛出时执行的程序)
}
catch(异常说明符 2)
{
	...		//处理程序(当异常说明符 2 被抛出时执行的程序)
}
	...		//更多的 catch

  A try block can be followed by one or more catch blocks, block execution exceptions thrown in the try, which will usually be a catch clause processing, once the catch clause execution ends, the program flow continues immediately after the last execution a clause in the statement following the catch.

  The catch clause exception specifier is a physical parameter of the parameter list, there are three forms:

catch(类型名)		//catch只需要了解异常的类型
catch(类型名 形参名)	//catch需要了解异常的类型之外的信息
catch(...)			//捕获所有异常

  Because it is impossible to know all the exceptions that may be thrown, then you can use catch(...), if catch(...)using, and in conjunction with other catch clause, then it must be the last, otherwise it back with the catch clauses are not matching detection.

3, execution of exception handling

(1) program flow reaches the try block, then execute the block in the try block, if there is no cause abnormal, then followed after the try block catch clause is not executed, the program from the last catch clause of the statement to continue execution ;

(2) throws an exception when will suspend execution of the current function, began to find the matching catch clause;

(3) First check whether the internal throw in the try, and if so, check the catch clauses to see if one of them and throw objects to match, if the matching catch is found, handle exceptions; if not, exit the current function and the release of a local object, and then continue to look in the calling function;

(4) If a match is found the catch, then handle the exception, if not found, then exit the calling function, and then continue to look at this function in a function call;

(5) along a nested function call chain continues up until a catch clause is found abnormal, can be found as long as the catch clause handles the exception, the catch clause proceeds, and continues in its processing procedure, when when the end of the catch, after a jump to the last sentence of the catch clause continues try block;

(6) if has not found the end of the final main function will be executed with the catch clause matches the exception thrown, the runtime library functions terminatewill be called automatically, terminatethe default function is the function terminates the program.

  Exception handling example:

//==========================================										   	
//	Filename : 异常处理实例							   	
//	Time     : 2019年6月26日						   
//	Author   : 柚子树					   	
//	Email    : [email protected]		   										   
//==========================================

#include <iostream>
using namespace std;

void Fun(int test)
{
	if (test == 0) throw test;	//抛出 int 型异常
	if (test == 1) throw 1.5;	//抛出 double 型异常
	if (test == 2) throw "abc";	//抛出 char* 型异常
	cout << "Fun调用正常结束!" << endl;
}

void Call_A(int test)
{
	try		//检测异常发生
	{
		Fun(test);
	}
	catch (int)
	{
		cout << "Call_A捕获异常int -> ";		//捕获异常
	}
	cout << "Call_A调用正常结束!" << endl;	//Call_A 正常结束时输出
}

void Call_B(int test)
{
	try
	{
		Call_A(test);
	}
	catch (double)
	{
		cout << "Call_B捕获异常double -> ";
	}
	catch (...)
	{
		cout << "Call_B捕获所有未知异常 -> ";
	}
	cout << "Call_B调用正常结束!" << endl;
}

int main()
{
	for (int i = 3; i >= 0; i--)
	{
		Call_B(i);
	}

	system("pause");
	return EXIT_SUCCESS;
}

  operation result:

Fun调用正常结束!
Call_A调用正常结束!
Call_B调用正常结束!
Call_B捕获所有未知异常 -> Call_B调用正常结束!
Call_B捕获异常double -> Call_B调用正常结束!
Call_A捕获异常int -> Call_A调用正常结束!
Call_B调用正常结束!

4, abnormal weight throw

In the catch clause, you can throw an exception again, for example:

try
{
	throw "Hello";		//抛出 char* 异常
}
catch (const char*)		//捕获 char* 异常
{
	throw;				//重新抛出 char* 异常至上一级函数
}
  • Wherein the throw without expression, the expression represents an exception is thrown in the try block detected again(throw "Hello")
  • Weight throw an exception that can not be try - catchcaptured, it can only be reached on a function

5, abnormal interface declaration

  In order to enhance the readability of the program, the user can easily know the function used by the function of which will throw an exception, you can list all the types of exceptions that function may throw in the declaration function. E.g:

  void Fun() throw (A, B, C, D);

  This indicates that the function Fun()can be thrown only and type A, B, C, D and its sub-types of exceptions, including without exception interface description statement in a function, the linear function may be any type of exception thrown. E.g:

  void Fun();

  A function not throw any type of exception can be the form of the statement:

  void Fun() throw ();

  Note: If a function throws an exception of its interface declarations are not permitted exceptions thrown, unexpectedthe function is called, the default behavior of this function is to call terminatea function to stop the program.

C ++ standard library of abnormal

Guess you like

Origin blog.csdn.net/weixin_42482896/article/details/93685099