异常,让一个函数可以在发现自己无法处理的错误时抛出一个异常,希望它的调用者可以直接或者间接处理这个问题。
之前写的一些小程序,几乎没有用到过异常处理。因为规模比较小,一般的问题在函数内就加上一些判断条件解决了,一般的做法就是返回一个表示错误的值(比如返回NULL指针),在调用的时候判断一下返回的值,虽然简单,但是功能并不强大,只适合小型项目。而大型的项目,如果这么搞就乱套了,所以就要用到异常处理这一套系统。
// ConsoleApplication3.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <string>
using namespace std;
//异常类
class NumberException{};
void NumOption(const int& a, const int& b)
{
try
{
if (b == 0)
throw NumberException();
cout<<a / b<<endl;
}
catch(const NumberException& e)
{
cout<<"Exception!"<<endl;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int a,b;
cin>>a;
cin>>b;
NumOption(a, b);
system("pause");
return 0;
}
// ConsoleApplication3.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <string>
using namespace std;
//异常类
class NumberException{};
//测试的类
class Test
{
public:
~Test()
{
cout<<"Test is destructed!"<<endl;
}
};
void NumOption(const int& a, const int& b)
{
try
{
Test test;
if (b == 0)
throw NumberException();
cout<<a / b<<endl;
}
catch(const NumberException& e)
{
cout<<"Exception!"<<endl;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int a,b;
cin>>a;
cin>>b;
NumOption(a, b);
system("pause");
return 0;
}
// ConsoleApplication3.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <string>
using namespace std;
//异常类
class NumberException{};
//派生的异常类
class ZeroException : public NumberException {};
void NumOption(const int& a, const int& b)
{
try
{
if (b == 0)
throw ZeroException();
cout<<a / b<<endl;
}
catch(const ZeroException& e)
{
cout<<"ZeroException!"<<endl;
}
catch(const NumberException& e)
{
cout<<"NumberException!"<<endl;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int a,b;
cin>>a;
cin>>b;
NumOption(a, b);
system("pause");
return 0;
}
结果:// ConsoleApplication3.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <string>
using namespace std;
//异常类
class NumberException{};
//派生的异常类
class ZeroException : public NumberException {};
void NumOption(const int& a, const int& b)
{
try
{
if (b == 0)
throw ZeroException();
cout<<a / b<<endl;
}
catch(const ZeroException& e)
{
cout<<"ZeroException!"<<endl;
throw;
}
catch (...)
{
cout<<"I can solve all Exception!"<<endl;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int a,b;
cin>>a;
cin>>b;
//嵌套异常处理
try
{
NumOption(a, b);
}
catch(const NumberException& e)
{
cout<<"NumberException!"<<endl;
}
system("pause");
return 0;
}
结果:catch (...)
{
cout<<"I can solve all Exceptions!"<<endl;
}
void fun() throw( A,B,C,D);这表明函数fun()可能并且只可能抛出类型(A,B,C,D)及其子类型的异常。
void fun();一个不会抛出任何类型异常的函数可以进行如下形式的声明:
void fun() thow();
原文地址:http://blog.csdn.net/puppet_master/article/details/46486925