Mechanism for exception handling:
1. If no exception occurs, continue executing the code in the try block, the catch clause associated with the TRY block is ignored, the program executes normally, and main () returns 0.
2. When the first try block throws an exception in the For loop, the for loop exits, and the try block exits to execute the catch clause of the pushonfull exception. Istack. Printstack () is no longer executed and is ignored.
3. If the second try block calls pop () to throw an exception, exit the for and try blocks to execute the catch clause of the poponempty exception.
4. When a statement throws an exception, the statement following the statement is skipped. The program execution is handed to the catch clause that handles the exception, and if no catch clause is able to handle the exception, it is passed to the terminate () defined in the C + + standard library.
The specific exception handling code is as follows:
#include <iostream> #include <iomanip> #include <string>using namespace std;//anomaly class Template<class Type>class pushonfull//Stack full exception {Public:pushonfull (string s): Str (s) {}type GetData () Const{return data;} string what ()//Output hint statement {return str;} BOOL Remalloc () {return true;} Private:string str;}; Template<class type>class poponempty//Stack null exception {Public:poponempty (string s): Str (s) {}string what () con ST//Output prompt statement {return str;} Private:string str;}; Template<class Type>class stack//stack {public:stack (int sz=size) {capacity = Sz>size?sz:siz E;base = new type[capacity];top = 0;} ~stack () {delete []base;base = NULL;} Public:bool isfull () const//judgment is full {return top >= capacity;} BOOL IsEmpty () const//determine if NULL {return top = = 0;} void Push (const Type &x)//into stack {if (Isfull ()) {string str ("stack full stack exception occurs!") "); throw pushonfull<type> (str); Throw exception}base[top++] = x;}void Pop ()//out stack {if (IsEmpty ()) {string str = "Stack empty stack exception occurred!"; Throw poponempty<type> (str); Throw exception}top--;} PRIVATE:ENUM{SIZE=8}; Type *base;size_t capacity;int top;}; void Main () {stack<int> St;try//exception handling {for (int i=1; i<=5; ++i) {St. Push (i);}} catch (pushonfull<int> &e)//catch Exception {cout<<e.what () <<endl;} Try//exception handling {for (int i=0; i<10; ++i) {St. Pop ();}} catch (poponempty<int> &exp)//catch Exception {cout<<exp.what () <<endl;}}
What is the problem I hope you can point out, thank you all ~
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"C + +" stack empty stack full exception handling