码迷,mamicode.com
首页 > 其他好文 > 详细

Exception-Handling

时间:2020-06-24 22:08:41      阅读:67      评论:0      收藏:0      [点我收藏+]

标签:enter   处理   exe   pac   exec   返回值   form   cannot   UNC   

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()?

Exception-Handling

标签:enter   处理   exe   pac   exec   返回值   form   cannot   UNC   

原文地址:https://www.cnblogs.com/Glov/p/13189810.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!