Facebook
From Harmless Hamerkop, 1 Year ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 131
  1. #include <iostream>
  2. #include <vector>
  3. #include <stdexcept>
  4.  
  5. int main() {
  6.     try {
  7.         std::vector<int> vec{3, 4, 3, 1};
  8.         int i{vec.at(4)}; // Throws an exception, std::out_of_range (indexing for vec is from 0-3 not 1-4)
  9.     }
  10.     // An exception handler, catches std::out_of_range, which is thrown by vec.at(4)
  11.     catch (std::out_of_range &e) {
  12.         std::cerr << "Accessing a non-existent element: " << e.what() << '\n';
  13.     }
  14.     // To catch any other standard library exceptions (they derive from std::exception)
  15.     catch (std::exception &e) {
  16.         std::cerr << "Exception thrown: " << e.what() << '\n';
  17.     }
  18.     // Catch any unrecognised exceptions (i.e. those which don't derive from std::exception)
  19.     catch (...) {
  20.         std::cerr << "Some fatal error\n";
  21.     }
  22. }