17 Exception Handling

目录:

  1. example that throw exception
  2. Rethrowing an exception
  3. Demonstrating stack unwinding.
  4. xx
  5. xxx
  6. xxx
  7. xx

 

 


1. example that throw exception

// example that throw exception

#include <iostream>
#include "DivideByZeroException.h"
using namespace std;


double quotient(int numerator, int denominator) {
    if (denominator == 0) {
        throw DivideByZeroException{};
    }
    return static_cast<double>(numerator) / denominator;
}

int main() {
    int number1;
    int number2;

    cout << "Enter two integers (end-of-file to end):";
    while (cin >> number1 >> number2) {
        try {
            double result{quotient(number1, number2)};
            cout << "The quotient is : " << result << endl;
        }
        catch (const DivideByZeroException& divideByZeroException) {
            cout << "Exception occured: " << divideByZeroException.what() << endl;
        }
        cout << "\nEnter tow integers (end-of-file to end): ";
    }
    cout << endl;
}


2. Rethrowing an exception

// Rethrowing an exception

#include <iostream>
#include <exception>
using namespace std;


void throwException(){
    try {
        cout << " Function throwException throws an exception\n";
        throw exception{};
    }
    catch (const exception&) {
        cout << " Exception handled in function throwException"
                << "\n Function throwException rethrows exception";
        throw;
    }
    cout << "This should not print\n";
}


int main() {
    try {
        cout << "\nmain invokes function throwException\n";
        throwException();
        cout << "This should not print\n";
    }
    catch (const exception&) {
        cout << "\n\nException handled in main\n";
    }
    cout << "Program control continues after catch in main\n";
}


3. Demonstrating stack unwinding.

// Demonstrating stack unwinding.

#include <iostream>
#include <stdexcept>
using namespace std;

void function3() {
    cout << "In function 3 " << endl;
    throw runtime_error{"runtime_error in function3"};
}


void function2() {
    cout << "function3 is called inside function2" << endl;
    function3();
}

void function1() {
    cout << "function2 is called inside function1" << endl;
    function2();
}

int main() {
    // invoke function
    try {
        cout << "function1 is called inside main" << endl;
        function1();
    }
    catch (const runtime_error& error) {
        cout << "Exception occurred: " << error.what() << endl;
        cout << "Exception handled in main" << endl;
    }
}


 

 


 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值