http://www.runoob.com/cplusplus/cpp-exceptions-handling.html
throw一个字符串提示
#include "stdafx.h"
#include <stdio.h>
#include <string>
#include <iostream>
#include <vector>
#include "Log.h"
using namespace std;
double division(int a, int b)
{
if (b == 0)
{
throw("Division by zero condition");
}
return a / b;
}
int main()
{
try
{
division(4,0);
}
catch (const char* e)
{
std::cout << e << std::endl;
}
return 0;
}
使用exception
#include "stdafx.h"
#include <stdio.h>
#include <string>
#include <iostream>
#include <vector>
#include "Log.h"
using namespace std;
int main()
{
try
{
throw exception("this is a error");
}
catch (exception& e)
{
std::cout << e.what() << std::endl;
}
return 0;
}
自定义一个异常
#include "stdafx.h"
#include <stdio.h>
#include <string>
#include <iostream>
#include <vector>
#include "Log.h"
using namespace std;
struct MyException :public exception
{
const char* what() const throw()
{
return "C++ Exception";
}
};
int main()
{
try
{
throw MyException();
}
catch (exception& e)
{
std::cout << "MyException caught" << std::endl;
std::cout << e.what() << std::endl;
}
return 0;
}