标签:enter 处理 exe pac exec 返回值 form cannot UNC
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;
}
#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";
}
宗旨:简单错误简单办,复杂错误异常办
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()?
标签:enter 处理 exe pac exec 返回值 form cannot UNC
原文地址:https://www.cnblogs.com/Glov/p/13189810.html