目录:
- example that throw exception
- Rethrowing an exception
- Demonstrating stack unwinding.
- xx
- xxx
- xxx
- 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;
}
}