zoukankan      html  css  js  c++  java
  • c++异常处理

    c++异常处理,以前学生阶段在最开始学习c++的时候,感觉真的好陌生,怎么理解都不明白,后来在工作中,再次遇到这种问题,决定写篇博客记录一下;

    注意是介绍,以及使用,关于底层怎么实现我并不关心,也没有精力去做这些事情;

    记住一点,exception这个类,是所有异常的最根本的来源;

    参考:www.cpluscplus.com中关于exception中的介绍以及demo案例;

    基本语句块:try....throw...catch,..,finally

    有两个练习题,分别使用try..catch,和throw...catch可以练练手,仔细体会一下,就知道是怎么回事儿,以及怎么处理所有的异常。

    题目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>
    10 #include <bitset>
    11 #include <cstdio>
    12 #include <limits>
    13 #include <vector>
    14 #include <climits>
    15 #include <cstring>
    16 #include <cstdlib>
    17 #include <fstream>
    18 #include <numeric>
    19 #include <sstream>
    20 #include <iostream>
    21 #include <algorithm>
    22 #include <unordered_map>
    23 
    24 using namespace std;
    25 
    26 
    27 int main(){
    28     string S;
    29     cin >> S;
    30     int interger = 0;
    31     try{
    32         interger = stoi(S);
    33     }catch(exception &e){
    34         cout << "Bad String" <<endl;
    35         return 0;
    36     }
    37     cout<< interger;
    38     return 0;
    39 }
    View Code

    题目2:https://www.hackerrank.com/challenges/30-more-exceptions

     1 //Write your code here
     2 class Calculator{
     3 public:
     4     int power(int n, int p){
     5         int res = 1;
     6         if(n < 0 || p < 0){
     7             throw domain_error("n and p should be non-negative");
     8         }
     9         else{
    10             while(p){
    11                 res *= n;
    12                 p--;
    13             }
    14             return res;
    15         }
    16     }    
    17 }; 
    View Code

    注意的地方,在throw xxx_exception的时候,一定要查查xxx_exception的用法,构造函数里面都是怎么定义的,可以传递那些参数,别傻乎乎的想当然;

    只知道不行动是纸上谈兵,只行动不思考更像是无头的苍蝇,要知行合一。
  • 相关阅读:
    kb-07线段树-12--二分查找区间边界
    kb-07线段树--11--区间多重该值多种查询
    kb-07线段树--10--dfs序建树
    kb-09-线段树--区间合并比较繁
    kb-07线段树-08--区间开根
    kb-07-RMQ线段树--07(动态规划)
    kb-07线段树-06离散化(与第四题类似)
    kb-07线段树-05-区间整体修改查询;(水)
    poj-2486-Apple Tree
    mnist的数据预处理
  • 原文地址:https://www.cnblogs.com/Spider-spiders/p/5814538.html
Copyright © 2011-2022 走看看