一、异常处理
#include<iostream>
using std::cout;
using std::endl;
using std::cin;
int main()
{
int x{ 0 }, y{ 0 };
cin >> x >> y;
try
{
if (y == 0) throw y;
cout << x / y;
}
catch (int& e)
{
cout << "the second number is :" << e << endl;
}
}
结果如上图所示。
二、bad_alloc异常
#include<iostream>
#include<exception>
#include<stdexcept>
#include<new>
using std::cout;
using std::endl;
int main()
{
try
{
for (int i = 0; i < 10000; i++)
{
auto* p = new long long int[700000];
cout << i << " array" << endl;
}
}
catch (std::bad_alloc& e)
{
cout << " exception: " << e.what() << endl;
}
}
结果如上图所示
三、bad_cast异常
#include<iostream>
#include<exception>
#include<stdexcept>
using std::cout;
using std::endl;
class Student
{
public:
Student() = default;
virtual void foo() {};
};
class Undergraduate :public Student {};
class Graduate : public Student{};
int main()
{
Undergraduate u;
Graduate g;
Student* s1 = &u;
Student* s2 = &g;
Graduate* p = dynamic_cast<Graduate *>(s2);
long x = reinterpret_cast<long>(p);
cout << x << endl;
Graduate* p2 = dynamic_cast<Graduate*>(s1);
if (p2 == nullptr)
{
cout << "cast s1 to Graduate failed" << endl;
}
else
{
cout << " cast s1 to Graduate * succeeded" << endl;
}
try{
Graduate& r1 = dynamic_cast<Graduate&>(u);
}
catch (std::bad_cast& e)
{
cout << "Exception " << e.what() << endl;
}
}
结果如上图所示。
四、out_of_range异常
#include<iostream>
#include<vector>
using std::cout;
using std::endl;
int main()
{
std::vector v{ 'a','b','c','d','e' };
try
{
for (int i = 0; i <= 5; i++)
{
// cout << v[i]; i=5越界
cout << v.at(i) << endl; //i=会抛出异常
}
}
catch (std::out_of_range& e)
{
cout << "Exception: " << e.what() << endl;
}
}
结果如上图所示。