Introduction to C++ try catch exception handling example

  • 2020-06-03 07:41:23
  • OfStack

In programming, we always expect our programs to be seamless, but this is almost impossible. Even if the program compiled by, at the same time also can realize the function needed, also does not mean it has been perfect, because when you run the program also may encounter exceptions, such as when we design a computing division for the user of the application, the user is likely to input zero divisor, again, for example, when we need to open a file is found that the file has been deleted... There are a lot of similar cases, for these special circumstances, not to prevent it is not good.

We usually want our programs to be able to handle exceptions without the program being inexplicably interrupted or aborted. All kinds of abnormal situations should be fully considered and dealt with in the design of the program.

In C++, a function detects an exception and returns it, a mechanism known as throwing an exception. When an exception is thrown, the function caller catches it and processes it, which is called exception capture.

C++ Added the throw keyword to throw exceptions, the catch keyword to catch exceptions, and the try keyword to try to catch exceptions. It is common to place the statement you are trying to catch in the try{} block and the exception-handling statement in the catch{} block.

The basic syntax for exception handling is described below. Let's start with the basic syntax for throwing exceptions under 1:
throw expression;
Throwing an exception consists of the throw keyword plus an expression. After throwing an exception, it is necessary to catch the exception and the exception handler, whose basic syntax is as follows:
try
{
// Statements that may throw an exception
}
catch (Exception type 1)
{
// Handler for exception type 1
}
catch (Exception type 2)
{
// Handler for exception type 2
}
/ /...
catch (Exception type n)
{
// Handler for exception type n
}

The exception thrown by throw is caught by the try block, and the exception handler in the catch block is run according to the exception type. The catch block order can be arbitrary, but it needs to be placed after the try block.

[Example 1] C++ Exception handling example:


#include<iostream>
using namespace std;
enum index{underflow, overflow};
int array_index(int *A, int n, int index);
int main()
{
  int *A = new int[10];
  for(int i=0; i<10; i++)
    A[i] = i;
  try
  {
    cout<<array_index(A,10,5)<<endl;
    cout<<array_index(A,10,-1)<<endl;
    cout<<array_index(A,10,15)<<endl;
  }
  catch(index e)
  {
    if(e == underflow)
    {
      cout<<"index underflow!"<<endl;
      exit(-1);
    }
    if(e == overflow)
    {
      cout<<"index overflow!"<<endl;
      exit(-1);
    }
  }
  return 0;
}
int array_index(int *A, int n, int index)
{
  if(index < 0) throw underflow;
  if(index > n-1) throw overflow;
  return A[index];
}

This example shows an exception catcher for an array that is out of bounds. The array_index function returns the value of the array index subscript and throws an exception if an exception occurs. The program statement in the try block is the statement where an exception may occur, and catch is the handling statement for an exception. At the beginning of program 1 we defined a global enumerated type variable index and defined two values, underflow and overflow, as the return values for throwing exceptions. When the main function asks to output the out-of-bounds array value, the array_index function is called. Once a scheduled exception is thrown, the exception is caught by try and processed according to the catch statement.

Earlier we described the new and delete dynamically allocated memory operators, which throw an bad_alloc exception if new or new[] cannot successfully allocate the requested one. When using the new or new[] operator to allocate dynamic memory, you can detect and catch exceptions that fail to allocate storage space as follows.

[Example 2] catches the exceptions thrown by new and new[] :


int * p;
try
{
  p = new int[10];
}
catch(bad_alloc)
{
  cerr<<"allocate failure!"<<endl;
  exit(-1);
}

In C, the exception is usually obtained by the return value of the function, but in this case, whether the function produces an exception or not can only be known by detecting the return value of the function. In C++, when a function throws a return value, the exception is handled even without the try and catch statements, and the default handler, unexpected, is automatically called for execution.

Here's what others have added


#include <exception> 
#include <iostream> 
using namespace std; 
 
/********************************** 
//project -> Properties -> C/C++ -> Code Generation --> Enable C++ Exceptions 
// choose  Yes with SEH Exceptions (/EHa)  so C++ the try catch  You can also catch null Pointers, memory runs out of bounds, 0 In addition to the abnormal  
// The default is select Yes (/EHsc) 
**********************************/ 
 
void TestIntType() 
{ 
  try 
  { 
    throw 1; 
  } 
  catch(...) 
  { 
    cout<< " in  try block  In the ,  Ready to throw 1 An abnormal ." << endl; 
  } 
} 
 
void TestDoubleType() 
{ 
  try 
  { 
    throw 0.5; 
  } 
  catch(...) 
  { 
    cout<< " in  try block  In the ,  Ready to throw 1 An abnormal ." << endl; 
  } 
} 
 
void TestEmptyPointType() 
{ 
  try 
  { 
    int* p = NULL; 
    *p = 3; 
  } 
  catch(...) 
  { 
    cout<< " Illegal address operation exception " << endl; 
  } 
} 
 
void TestDivZeroType() 
{ 
  try 
  { 
    int b = 0; 
    int a = 3/b; 
  } 
  catch(...) 
  { 
    cout<< "0 In addition to the abnormal " << endl; 
  } 
} 
 
void TestMemoryOutType() 
{ 
  int * a = new int[4]; 
  try 
  { 
    for (int i = 0; i<245; i++) 
    { 
      a++; 
    } 
    *a = 3; 
  } 
  catch(...) 
  { 
    cout<< " Memory out-of-bounds exceptions " << endl; 
  } 
} 
 
int main(int argc, char* argv[]) 
{ 
  TestEmptyPointType(); 
  //TestDivZeroType(); 
  TestMemoryOutType(); 
  return 1; 
}

Related articles: