C + + exception handling, the previous student stage in the first time to learn C + +, feel really good unfamiliar, how to understand do not understand, later in the work, again encountered this problem, decided to write a blog record;
Note is the introduction, as well as the use, about the bottom how to achieve I do not care, and do not have the energy to do these things;
Remember one thing, exception this class, is the most fundamental source of all anomalies;
Reference: Www.cpluscplus.com in the exception in the introduction and demo case;
Base statement block: Try....throw...catch,.., finally
There are two exercises, each using try. Catch, and throw...catch can practice practiced hand, carefully understand, know what is going on, and how to deal with all the anomalies.
Topic 1:https://www.hackerrank.com/challenges/30-exceptions-string-to-integer
1#include <map>2#include <Set>3#include <list>4#include <cmath>5#include <ctime>6#include <deque>7#include <queue>8#include <stack>9#include <string>Ten#include <bitset> One#include <cstdio> A#include <limits> -#include <vector> -#include <climits> the#include <cstring> -#include <cstdlib> -#include <fstream> -#include <numeric> +#include <sstream> -#include <iostream> +#include <algorithm> A#include <unordered_map> at - using namespacestd; - - - intMain () { - stringS; inCIN >>S; - intInterger =0; to Try{ +Interger =Stoi (S); -}Catch(Exception &e) { thecout <<"Bad String"<<Endl; * return 0; $ }Panax Notoginsengcout<<Interger; - return 0; the}View Code
Topic 2:https://www.hackerrank.com/challenges/30-more-exceptions
1 //Write Your code here2 classcalculator{3 Public:4 intPowerintNintp) {5 intres =1;6 if(N <0|| P <0){7 ThrowDomain_error ("N and P should be non-negative");8 }9 Else{Ten while(p) { OneRes *=N; Ap--; - } - returnRes; the } - } -};View Code
Note where, in the throw xxx_exception, be sure to check the usage of xxx_exception, the constructor is how to define the function, you can pass those parameters, do not take it for granted;
C + + exception handling