avr39ripe

cppExceptionBaseExample

Aug 20th, 2021
967
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2.  
  3. // 1 , 2 , 3, 4 , 5 , 6, 7, 8 ,9 ,10
  4. //          100         112
  5.  
  6. class Test
  7. {
  8. public:
  9.     Test() { std::cout << "Test ctor\n"; }
  10.     ~Test() { std::cout << "Test dtor\n"; }
  11. };
  12.  
  13.  
  14. int linearSearch(const int* begin, const int* const end, int key)
  15. {
  16.     Test test;
  17.     auto start{ begin };
  18.  
  19.     while (begin != end)
  20.     {
  21.         if (*begin == key) { return begin - start; }
  22.         ++begin;
  23.     }
  24.     //std::cout << "Key don't found!\n";
  25.     throw (float)-42;
  26.     return -1;
  27. }
  28.  
  29.  
  30. int crash(int par)
  31. {
  32.     std::cout << "Crash starts\n";
  33.     if (par < 0)
  34.     {
  35.         throw true;
  36.     }
  37.     std::cout << "Crash ends\n";
  38.     return 42;
  39. }
  40.  
  41.  
  42. int main()
  43. {
  44.     const int arrSize{ 10 };
  45.     int arr[arrSize]{ 1,2,3,4,5,6,7,8,9,10 };
  46.  
  47.     int exc{ 42 };
  48.  
  49.    
  50.  
  51.     std::cout << "Program starts\n";
  52.     try
  53.     {
  54.        
  55.  
  56.         try
  57.         {
  58.             std::cout << "Pre exception\n";
  59.             //std::cout << "Answer is: .... " << crash(-1) << '\n';
  60.  
  61.             int key{ 101 };
  62.  
  63.             std::cout << "Key ->" << key << " was found at " << linearSearch(arr+2, arr + arrSize, key) << '\n';
  64.  
  65.             std::cout << "Post exception\n";
  66.         }
  67.  
  68.         catch (int exception)
  69.         {
  70.             if (exception == -42)
  71.             {
  72.                 std::cout << "OOpps! We do not found super important data in array!\n";
  73.             }
  74.             else
  75.             {
  76.                 std::cout << "Bad things, int code: " << exception << '\n';
  77.             }
  78.            
  79.         }
  80.  
  81.         catch (char exception)
  82.         {
  83.             std::cout << "Bad things, char code: " << exception << '\n';
  84.         }
  85.  
  86.         //catch (...)
  87.         //{
  88.         //  std::cout << "Bad things, very bad!\n";
  89.         //}
  90.     }
  91.  
  92.     catch (float ex)
  93.     {
  94.         std::cout << "External try block float exception: " << ex << '\n';
  95.     }
  96.  
  97.    
  98.  
  99.     std::cout << "After exception processing\n";
  100.  
  101.     std::cout << "Program ends\n";
  102.     return 0;
  103. }
  104.  
RAW Paste Data