1. Implementation of exception handling
#include <iostream>using namespacestd;DoubleDivideDouble,Double);intMain () {Doublef1=0.0, f2=0.0; Try{cout<<"f1/f2="<<divide (F1,F2) <<Endl; } Catch(Double) {cout<<"be removed by 0"<<Endl; } return 0;}DoubleDivideDoubleXDoubley) { if(y==0) Throw 0.0; returnx/y;}
Operation Result: divisible by 0
#include <iostream>using namespacestd;classoutofbounds{ Public: Outofbounds (inta) {i=A; } intIndexvalue () {returni; }Private: inti;};classarray{ Public: int&operator[](inti) { if(i<0|| i>=Ten){ Throwoutofbounds (i); returnA[i]; } }Private: inta[Ten];};intMain () {Array A; Try{a[3]= -; cout<<"A[3]"<<a[3]<<Endl; a[ -]= -; cout<<"a[100]"<<a[ -]<<Endl; } Catch(outofbounds error) {cout<<"Subscript Value"<<error.indexvalue () <<"Out of bounds.\n"; } return 0;}
overloaded operation symbol [], for cross check. If the subscript is negative or greater than 10, an error occurs.
Note: the & symbol for the first line of the overloaded operator operator[] function is required. Because this function returns not only the value of the array element, but also the element itself (that is, the left value), so that an expression such as a[3] is used on the left side of an assignment statement, such as an expression a[100]=1000;
Operation Result:
2 Re-throwing exceptions and exception specifications
#include <iostream>using namespacestd;voidh () {Throw 0;}voidg () {Try{h (); } Catch(int) {cout<<"Catch in g\n"; Throw; }}intMain () {Try{g (); } Catch(int) {cout<<"Catch in main\n"; } return 0;}
Operation Result:
3. Exception classes in the standard library
#include <iostream>#include<exception>using namespacestd;intMain () {Try{exception theerror;//declares an object of the standard C + + Exception class Exceptio Throw(Theerror);//object that throws the exception class } Catch(ConstException &theerror) {//capturing objects of the standard C + + Exception classCout<<theerror.what () <<endl;//Use the WAHT member function to display the cause of the error } Try{logic_error Thelogicerror ("Logic error!");//declares an object of the standard C + + Exception class Logic_error Throw(Thelogicerror);//object that throws the exception class } Catch(ConstException &thelogicerror) {//capturing objects of the standard C + + Exception classCout<<thelogicerror.what () <<endl;//Use the WAHT member function to display the cause of the error } return 0;}
Operation Result:
C + + exception handling mechanism