#include <iostream>#include<string>#include<vector>#include<stdexcept>using namespacestd;//Different catch blocks can be taken for different exceptions to captureintMainintargcConst Char*argv[]) { Try { inti; CIN>>i; if(i = =0) ThrowRuntime_error ("run-time error occurs"); Send a Runtime_error exceptionElse if(i = =1) ThrowInvalid_argument ("Illegal parameters"); } Catch(Runtime_error &e) {cout<<"Runtime_error:"<< e.what () <<Endl; Error message is stored in E.what ()}Catch(Invalid_argument &e) {cout<<"invalid_argument:"<< e.what () <<Endl; } cout<<"Continue running"<<Endl; return 0;}
#include <iostream>#include<string>#include<vector>#include<stdexcept>using namespacestd;//the exception is not captured, as the core dumpintMainintargcConst Char*argv[]) { Try { inti; CIN>>i; if(i = =0) ThrowRuntime_error ("run-time error occurs"); Else if(i = =1) ThrowInvalid_argument ("Illegal parameters"); } Catch(Runtime_error &e) {cout<<"Runtime_error:"<< e.what () <<Endl; } cout<<"Continue running"<<Endl; return 0;}
Skip catch to continue execution of subsequent code if no exception is caught
Try & Catch is a block of statements that is very useful for handling exceptions. More practice.
Here is an important template
#include <iostream>#include<string>#include<vector>#include<stdexcept>using namespacestd;//Different catch blocks can be taken for different exceptions to capture//for a part can be processed uniformlyintMainintargcConst Char*argv[]) { Try { inti; CIN>>i; if(i = =0) ThrowRuntime_error ("run-time error occurs"); Else if(i = =1) ThrowInvalid_argument ("Illegal parameters"); Else if(i = =2) ThrowLogic_error ("Logic Error"); Else ThrowOut_of_range ("Out of bounds error"); } Catch(...)//can catch all the anomalies { } Catch(Exception &e) {cout<<"Exception Information:"<< e.what () <<Endl; } Catch(Runtime_error &e) {cout<<"Runtime_error:"<< e.what () <<Endl; } Catch(Invalid_argument &e) {cout<<"invalid_argument:"<< e.what () <<Endl; } cout<<"Continue running"<<Endl; return 0;}
C + + Learning Path: Try&catch statement block handling exceptions