一、异常处理关键词?
C ++提供了以下专用关键字。
try:表示可能引发异常的代码块。
catch:表示抛出特定异常时执行的代码块。
throw:用于引发异常。也用于列出函数引发但无法自行处理的异常。
二、为什么要进行异常处理?
(1)错误处理代码与普通代码的分离:在传统的错误处理代码中,总是存在其他条件来处理错误。这些条件和处理错误的代码与正常流程混在一起。这使代码的可读性和可维护性较差。使用try catch块,用于错误处理的代码将与正常流程分开。
(2)函数方法可以处理他们选择的任何异常:函数可以引发许多异常,但是可以选择处理其中的一些异常。引发但未被捕获的其他异常可以由调用方处理。如果呼叫者选择不捕获它们,则异常由呼叫者的呼叫者处理。
在C ++中,函数可以使用throw关键字指定其引发的异常。此函数的调用者必须以某种方式处理异常(通过再次指定它或捕获它)
(3)错误类型分组:在C ++中,基本类型和对象都可以作为异常抛出。我们可以创建异常对象的层次结构,在名称空间或类中对异常进行分组,并根据类型对它们进行分类。
三、使用方法
(1)基本使用方法
#include <iostream>
using namespace std;
int main()
{
int x = -1;
// Some code
cout << "Before try \n";
try {
cout << "Inside try \n";
if (x < 0)
{
throw x;
cout << "After throw (Never executed) \n";
}
}
catch (int x ) {
cout << "Exception Caught \n";
}
cout << "After catch (Will be executed) \n";
return 0;
}
运行结果:
Before try
Inside try
Exception Caught
After catch (Will be executed)
(2)有一个特殊的catch块,称为“ catch all” catch(…),可用于捕获所有类型的异常。例如,在下面的程序中,将引发int作为异常,但是没有用于int的catch块,因此将执行catch(…)块。
#include <iostream>
using namespace std;
int main()
{
try {
throw 404;
}
catch (char *excp) {
cout << "Caught " << excp;
}
catch (...) {
cout << "Default Exception\n";
}
return 0;
}
运行结果:
Default Exception
(3)从函数捕获异常
#include <iostream>
using namespace std;
void fun(int *ptr, int x)
{
if (ptr == NULL)
throw ptr;
if (x == 0)
throw x;
/* Some functionality */
}
int main()
{
try {
fun(NULL, 0);
}
catch(...) {
cout << "Caught exception from fun()";
}
return 0;
}
运行结果:
Caught exception from fun()
(4)引发异常时,在将控件转移到catch块之前,将破坏在try块内部创建的所有对象。
#include <iostream>
using namespace std;
class Test {
public:
Test() { cout << "Constructor of Test " << endl; }
~Test() { cout << "Destructor of Test " << endl; }
};
int main()
{
try {
Test t1;
throw 10;
}
catch (int i) {
cout << "Caught " << i << endl;
}
}
运行结果:
Constructor of Test
Destructor of Test
Caught 10
(5)通过继承和重载 exception 类来定义新的异常。
#include <iostream>
#include <exception>
using namespace std;
struct MyException : public exception
{
const char * what () const throw ()
{
return "C++ Exception";
}
};
int main()
{
try
{
throw MyException();
}
catch(MyException& e)
{
std::cout << "MyException caught" << std::endl;
std::cout << e.what() << std::endl;
}
catch(std::exception& e)
{
//other exception
}
}
运行结果:
MyException caught
C++ Exception