Latest web development tutorials

C ++ exception handling

Exceptions are procedural issues arising during execution. C ++ exception refers to special happens when the program is running, such as attempts to divide by zero operation.

Exception is provided a transfer program control way. C ++ exception handling involves threekeywords: try, catch, throw.

  • throw: When problems arise, the program will throw an exception.This is done by using thethrow keyword to complete.
  • catch: where you want to deal with the problem, an exception is caught by an exception handler.catch keyword is used to catch exceptions.
  • try: tryblock code identifies a specific exception is activated. Behind it is usually followed by one or more catch blocks.

If there is a block throws an exception, catch the exception method usestry and catchkeywords. try placing a block of code might throw an exception, try block code is known as code-protected. Use try / catch statement syntax is as follows:

try
{
   // 保护代码
}catch( ExceptionName e1 )
{
   // catch 块
}catch( ExceptionName e2 )
{
   // catch 块
}catch( ExceptionName eN )
{
   // catch 块
}

If youtry block in different contexts will throw a different exception, this time you can try to list multiple catchstatements to catch different types of exceptions.

Throw an exception

You can use thethrow statement anywhere in the code block throws an exception.Operand throw statement can be any expression type of the result of the expression determines the type of exception thrown.

The following is an exception Try zero divided by examples:

double division(int a, int b)
{
   if( b == 0 )
   {
      throw "Division by zero condition!";
   }
   return (a/b);
}

Catch the exception

catch block behind the tryblock to capture exceptions. You can specify the type of exception you want to capture, which is declared by the exception in parentheses after the catch keyword decisions.

try
{
   // 保护代码
}catch( ExceptionName e )
{
  // 处理 ExceptionName 异常的代码
}

The above code will capture a typeExceptionName exception.If you want to catch block can handle any type of exception thrown try block, you must use the exception in parentheses ellipsis ... statement, as follows:

try
{
   // 保护代码
}catch(...)
{
  // 能处理任何异常的代码
}

Here is an example of a division by zero throws an exception, and the exception is caught in the catch block.

#include <iostream>
using namespace std;

double division(int a, int b)
{
   if( b == 0 )
   {
      throw "Division by zero condition!";
   }
   return (a/b);
}

int main ()
{
   int x = 50;
   int y = 0;
   double z = 0;
 
   try {
     z = division(x, y);
     cout << z << endl;
   }catch (const char* msg) {
     cerr << msg << endl;
   }

   return 0;
}

Since we throw a typeconst char * exception, therefore, when the catch that exception, we must use const char * in the catch block.When the above code is compiled and executed, it produces the following results:

Division by zero condition!

C ++ standard exceptions

C ++ provides a set of standard exceptions defined in<exception>, we can use these standard exceptions in the program.They are based on parent-child class hierarchy organized as follows:

C ++ exception hierarchy

The following table is a description of each of the above hierarchy appear abnormal:

异常 描述
std::exception 该异常是所有标准 C++ 异常的父类。
std::bad_alloc 该异常可以通过new抛出。
std::bad_cast 该异常可以通过dynamic_cast抛出。
std::bad_exception 这在处理 C++ 程序中无法预期的异常时非常有用。
std::bad_typeid 该异常可以通过typeid抛出。
std::logic_error 理论上可以通过读取代码来检测到的异常。
std::domain_error 当使用了一个无效的数学域时,会抛出该异常。
std::invalid_argument 当使用了无效的参数时,会抛出该异常。
std::length_error 当创建了太长的 std::string 时,会抛出该异常。
std::out_of_range 该异常可以通过方法抛出,例如 std::vector 和 std::bitset<>::operator[]()。
std::runtime_error 理论上不可以通过读取代码来检测到的异常。
std::overflow_error 当发生数学上溢时,会抛出该异常。
std::range_error 当尝试存储超出范围的值时,会抛出该异常。
std::underflow_error 当发生数学下溢时,会抛出该异常。

Define a new exception

You can define new exception byexception class inheritance and overloading.The following example demonstrates how to use std :: exception class to implement their own exceptions:

#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)
  {
    //其他的错误
  }
}

This produces the following results:

MyException caught
C++ Exception

Here, what () method is a public exception class provided that it has been overloaded all sub exception classes.This will return the cause of this exception generated.