Exception-Handling
Posted glov
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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()?
以上是关于Exception-Handling的主要内容,如果未能解决你的问题,请参考以下文章