1、C++标准异常类用法
#include <iostream>
#include <exception>
using namespace std;
int main () {
try
{
int* myarray= new int[100000];
}
catch (exception& e)
{
cout << "Standard exception: " << e.what() << endl;
}
return 0;
}
2、自定义异常类用法
#include <iostream>
#include <exception>
using namespace std;
//可以自己定义Exception
class myexception: public exception
{
virtual const char* what() const throw()
{
return "My exception happened";
}
}myex;
int main () {
try
{
if(true) //如果,则抛出异常;
throw myex;
}
catch (exception& e)
{
cout << e.what() << endl;
}
return 0;
}
3、一个try,多个catch用法
#include <iostream>
#include <exception>
using namespace std;
int main () {
try
{
throw 1;
throw "error";
}
catch(char *str)
{
cout << str << endl;
}
catch(int i)
{
cout << i << endl;
}
}
4、catch(…)的作用
catch(…)能够捕获多种数据类型的异常对象,所以它提供给程序员一种对异常对象更好的控制手段,使开发的软件系统有很好的可靠性。
void Func()
{
try
{
// 这里的程序代码完成真正复杂的计算工作,这些代码在执行过程中
// 有可能抛出DataType1、DataType2和DataType3类型的异常对象。
}
catch(DataType1& d1)
{
}
catch(DataType2& d2)
{
}
catch(DataType3& d3)
{
}
/********************************************************* 注意上面try block中可能抛出的DataType1、DataType2和DataType3三
种类型的异常对象在前面都已经有对应的catch block来处理。但为什么
还要在最后再定义一个catch(…) block呢?这就是为了有更好的安全性和
可靠性,避免上面的try block抛出了其它未考虑到的异常对象时导致的程
序出现意外崩溃的严重后果,而且这在用VC开发的系统上更特别有效,因
为catch(…)能捕获系统出现的异常,而系统异常往往令程序员头痛了,现
在系统一般都比较复杂,而且由很多人共同开发,一不小心就会导致一个
指针变量指向了其它非法区域,结果意外灾难不幸发生了。catch(…)为这种
潜在的隐患提供了一种有效的补救措施。 *********************************************************/
catch(…)
{
}
}
5、C++标准异常类
class exception
{
public:
exception() throw();
exception(const exception& rhs) throw();
exception& operator=(const exception& rhs) throw();
virtual ~exception() throw();
virtual const char *what() const throw();
};
C++有很多的标准异常类:
namespace std
{
//exception派生
class logic_error; //逻辑错误,在程序运行前可以检测出来
//logic_error派生
class domain_error; //违反了前置条件
class invalid_argument; //指出函数的一个无效参数
class length_error; //指出有一个超过类型size_t的最大可表现值长度的对象的企图
class out_of_range; //参数越界
class bad_cast; //在运行时类型识别中有一个无效的dynamic_cast表达式
class bad_typeid; //报告在表达试typeid(*p)中有一个空指针p
//exception派生
class runtime_error; //运行时错误,仅在程序运行中检测到
//runtime_error派生
class range_error; //违反后置条件
class overflow_error; //报告一个算术溢出
class bad_alloc; //存储分配错误
}
6、一些样例
#include "try_catch.hpp"
#include <iostream>
#include <exception>
#include <vector>
//
// reference: http://www.cplusplus.com/doc/tutorial/exceptions/
int test_exception1()
{
try {
throw 20;
}
catch (int e) {
std::cout << "An exception occurred. Exception Nr. " << e << '\n';
}
return 0;
}
class myexception : public std::exception
{
virtual const char* what() const throw()
{
return "My exception happened";
}
} myex;
int test_exception2()
{
try {
throw myex;
}
catch (std::exception& e) { // catches exception objects by reference (notice the ampersand & after the type)
std::cout << e.what() << '\n';
}
return 0;
}
int test_exception3()
{
/*
exception description
bad_alloc thrown by new on allocation failure
bad_cast thrown by dynamic_cast when it fails in a dynamic cast
bad_exception thrown by certain dynamic exception specifiers
bad_typeid thrown by typeid
bad_function_call thrown by empty function objects
bad_weak_ptr thrown by shared_ptr when passed a bad weak_ptr
*/
try {
int* myarray = new int[1000];
}
catch (std::exception& e) { // Takes a reference to an 'exception' object
std::cout << "Standard exception: " << e.what() << std::endl;
}
return 0;
}
///
// reference: http://en.cppreference.com/w/cpp/language/try_catch
int test_exception4()
{
try {
std::cout << "Throwing an integer exception...\n";
throw 42;
}
catch (int i) {
std::cout << " the integer exception was caught, with value: " << i << '\n';
}
try {
std::cout << "Creating a vector of size 5... \n";
std::vector<int> v(5);
std::cout << "Accessing the 11th element of the vector...\n";
std::cout << v.at(10); // vector::at() throws std::out_of_range
}
catch (const std::exception& e) { // caught by reference to base
std::cout << " a standard exception was caught, with message '"
<< e.what() << "'\n";
}
return 0;
}
/
// reference: https://www.tutorialspoint.com/cplusplus/cpp_exceptions_handling.htm
static int division(int a, int b) {
if (b == 0) {
throw "Division by zero condition!";
}
return (a / b);
}
int test_exception5()
{
int x{ 50 }, y{ 0 }, z{ 0 };
try {
z = division(x, y);
std::cout << z << std::endl;
}
catch (const char* msg) {
std::cerr << msg << std::endl;
}
return 0;
}
struct MyException : public std::exception
{
const char * what() const throw () {
return "C++ Exception";
}
};
int test_exception6()
{
try {
throw MyException();
}
catch (MyException& e) {
std::cout << "MyException caught" << std::endl;
std::cout << e.what() << std::endl;
}
catch (std::exception& e) {
//Other errors
}
return 0;
}
int test_exception7()
{
try {
char* str = nullptr;
str = new char[10];
if (str == nullptr) throw "Allocation failure";
for (int n = 0; n <= 100; n++) {
if (n > 9) throw n;
str[n] = 'z';
}
}
catch (int i) {
std::cout << "Exception: ";
std::cout << "index " << i << " is out of range" << std::endl;
}
catch (char * str) {
std::cout << "Exception: " << str << std::endl;
}
return 0;
}
参考:
try catch的详细分析:
https://www.cnblogs.com/MrYuan/p/4800257.html