C/C++ 异常处理

C

C++

 1 #include<iostream>
 2 # include<exception>
 3 using namespace std;
 4 
 5 int abc(int a, int b, int c){
 6     if(a <= 0 || b <= 0 || c <= 0)
 7         throw "abc can`t be 0"; // 抛出abc不能等于0的异常 
 8     return a + b + c;
 9 }
10 /* 
11 int abc(float a, float b, float c){
12     return a * b * c;
13 }
14 */ 
15 double abc(double a, double b, double c){
16     double result = a * b * c;
17     cout << result << endl;
18     return result;
19 }
20 int main(){
21     try{
22         cout << abc(1, 2, 0) << endl;
23     }
24     
25     catch(const char *e){ //  const 是关键的,如果没有const,达不到预期效果 
26         cout << e << endl;
27     }
28     
29     return 0;
30 } 

  如果throw没有用try语句进行捕获,throw语句结束后,抛出异常的函数继续执行。

  try和catch语句的内容必须由大括号“{}”括起,即使只有一条语句。因为大括号内相当于一个区域,故在try中定义的变量为try区域的临时变量,catch区域无法访问。

结果:

第25行,如果没有const

 

原文地址:https://www.cnblogs.com/uhanhi/p/12963699.html