Try
Throw
CatchIf you find an exception that you cannot handle in a program, you can use the
ThrowAn expression to throw the exception.
TryThe compound statement after the clause is the protection of the code snippet. If you anticipate that a piece of code might have an exception, place it in the
TryAfter the clause. If an exception is encountered, the
ThrowAn expression throws the exception. Execution process:
- The program executes correctly into the Try statement and executes the code in it.
- If no exception is caused during execution within the protection segment, then the catch clause following the Try is not executed. The program executes the statement following the last Catch clause followed by the Try block After the exception is thrown.
- When a program executes to a Throw expression, an exception object is created. If the throw point of the exception is within a try clause itself, then the Catch clause after the try statement checks whether the exception type matches the declared type in order, and if the exception is thrown by itself in a try clause, or throws an exception that does not match the type declared by each Catch clause, ends the execution of the current function, returns to the calling point of the current function, takes the call point as the throw point of the exception, and repeats the process. Until the exception is caught by a catch statement.
- If a Catch clause that matches the thrown exception is never found, the final Main function stops executing.
- If a matching catch clause is found, the compound statement after the catch clause executes. After the compound statement is executed, the current Try block is finished.
the trhow matches the catch:
- The type of exception declared in a catch clause is the type or reference that throws the exception object.
- The exception type declared in the catch clause is the public base class of the type that throws the exception object or its reference.
- Thrown exceptions are similar and the exception types declared in a catch clause are pointer types, and the former to the latter can be implicitly converted.
- catch (..... ) can match all exceptions.
#include <iostream>using namespace std;int divide (int x,int y){if (y==0)throw x;return x/y;}int main (){Try {cout<< "5/2=" <<divide (5,2) <<endl;cout<< "8/0=" <<divide (8,0) <<endl;cout<< "7/1=" <<divide (7,1) <<endl; }catch (int e) {cout<< "Error" <<e<< "is divided by zero!" <<endl; }cout<< "That ' s Ok" <<endl;return 0;}
Output:5/2=2 Error 8 is divided by zero! That ' s Ok
powerful feature: the ability to automatically call destructors for all local objects constructed before the exception is thrown! With a throw expression without an operand, you can throw the exception that is currently being handled, so that an expression can only appear in a catch clause or in a function that is called inside a catch clause.
C + + exception handling