• Exception-Handling


    Exception-Handling Overview

    Example Snippet for try-throw-catch (踹扔抓示例)

    try {
    
     Code to try;
    
     throw an exception  (1) with a throw statement           						 
                         (2) or from function;
    
     More code to try;
    
    }
    
    catch (type e) {
    
     Code to process the exception;
    
    }
    

    TWO way to deal with" divide an integer by 0 " (两种处理被0除的方法)

    • (1) use *if* statement (使用if语句)
    • (2) use *exception handling* (使用异常处理)
    #include <iostream>
    using namespace std;
    int main(){
    	cout << "Enter two integers";
    	int number1, number2;
    	cin >> number1 >> number2;
    
    	try{
    		if (number2 == 0){
    			throw number1;
    		}
    
    		cout << number1 << "/" << number2 << " is " << (number1 / number2) << endl;
    				
    	}
    	catch(int e){
    		cout << "Exception: an integer " << e << " cannot be divided by zero" << endl;
    	}
    
    	cout << "Execution continues";
    
    }
    

    Exception-Handling Advantages

    宗旨:简单错误简单办,复杂错误异常办

    Advantages: bring the exceptional information in callee to the caller

    用异常处理:

    int quotient(int number1, 
    
                 int number2) {
    
      if (number2 == 0) 
    
        throw number1; 
    
      return number1 / number2;
    
    } 
    
    int main() {
    
      try {
    
        int x = quotient(1, 0);
    
      } catch (int) {
    
        std::cout << "除数为0!";
    
      }
    
    }
    

    若不用异常处理:

    quotient()如何告诉 main() "number2 有问题"?

    (1) 用返回值?

    if(number2 == 0) return x; //x应该是0还是1?
    

    (2) 用指针/引用类型的参数?

    int quotient(int n1, int n2, int &s){
    
      if(n2 == 0) s=-1; //求商,函数要3个参数?
    
    }
    

    (3) 如果采用 f(g(h(quotient(x,y)))); 怎样将错误从quotient() 传到 f()?

  • 相关阅读:
    调试某狐木马驱动被杀后系统卡死开机
    情景剧:C/C++中的未定义行为(undefined behavior)
    汇编概念辨析(Intel/AT&T syntax、GAS、NASM)
    软考准考证打印设置(IE1909)
    基于redis的分布式锁 RedissonLock解锁异常解决
    深入理解synchronized
    单利模式
    归并排序
    旧电脑硬盘回收
    萤石、乐橙、3D
  • 原文地址:https://www.cnblogs.com/Glov/p/13189810.html
Copyright © 2020-2023  润新知