Exception Handling (C language)
-
-
if () { ... } else { ... }
-
setjmp和longjmp
. 1 #include <stdio.h> 2 #include <setjmp.h> . 3 . 4 the jmp_buf the env = { 0 }; . 5 . 6 int divId ( int A, int B) . 7 { . 8 IF (B == 0 ) . 9 { 10 longjmp (the env, . 1 ); // 2. restore the saved context, and set the return value setjmp (second parameter) . 11 } 12 is the else 13 is { 14 return a / B; 15 } 16 } . 17 18 is int main () . 19 { 20 is IF (the setjmp (the env) == 0 ) // 1. save current context, returns 0; 21 // 3. After calling longjmp, back here, returns the return value set longjmp the value 22 is { 23 is the printf ( " divId (. 1, 0) D =% \ n- " , divId ( . 1 , 0 )); 24 } 25 the else 26 is { 27 the printf ( " Unexpected !! \ n- " ); 28 } 29 30 return 0 ; 31 is }
Exception Handling (C ++ language)
-
-
The exception is thrown and handled separately, more reasonable, flexible
-
try { ... } catch { ... }
-
Use the keyword throw throw, throw an exception can be of any type, base type, class types and custom types can be
-
After an exception is thrown, it will catch up in order to find a place along the sequence of function calls, if not found, the program terminates; if found (matched to catch), enter the catch is processed, the program does not terminate
-
A plurality of connection can try catch, catch matching rule is as follows:
-
Each exception can only be a catch branch processing
-
The matching process to match the top down
-
The rule matching process is similar to a function call, but no implicit type conversion, tight parameter matching
-
Thrown initialization parameters will be used to catch anomalies
-
Matching base class exception subclass
-
C ++ does not have to use exceptions provided in the library, you can use custom exception
-
Variable parameters generally used as a catch last branch, do ceiling processing
-
-
try {...} catch {...} can be nested, meaning the project is to re-interpret abnormal, do compatible processing
. 1 #include <the iostream> 2 #include < String > . 3 . 4 the using namespace STD; . 5 . 6 void FUNC () // nested, an abnormality of repackaging explained . 7 { . 8 the try . 9 { 10 the throw 2 ; . 11 } 12 is the catch ( int I) 13 is { 14 IF (I == 2 ) 15 { 16 the throw String ( " error NO 2"); 17 } 18 } 19 } 20 21 int main() 22 { 23 try 24 { 25 throw 1; 26 } 27 catch(int e) 28 { 29 cout<< "catch(int e)" << endl; 30 } 31 catch(...) 32 { 33 cout<< "catch(...)" <<endl; 34 } 35 36 try 37 { 38 func(); 39 } 40 catch(string e) 41 { 42 cout<< e <<endl; 43 } 44 45 return 0; 46 }