fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <exception>
  4.  
  5. using namespace std;
  6.  
  7. class MyException : public exception
  8. {
  9. public:
  10. // exception specifications (throw lists) are deprecated.
  11. // use the noexcept keyword to indicate a function doesn't throw.
  12. virtual const char* what() const noexcept
  13. {
  14. return "Something bad happened";
  15. }
  16. };
  17.  
  18. class Test
  19. {
  20. public:
  21. void goesWrong() // exception specifications are deprecated
  22. {
  23. throw MyException();
  24. }
  25. };
  26.  
  27. int main()
  28. {
  29. Test test;
  30.  
  31. try
  32. {
  33. test.goesWrong();
  34. }
  35. catch (exception &e)
  36. {
  37. cout << "First catch: ";
  38. cout << e.what() << '\n';
  39. }
  40.  
  41. try
  42. {
  43. test.goesWrong();
  44. }
  45. catch (exception e)
  46. {
  47. cout << "Second catch: ";
  48. cout << e.what() << '\n';
  49. }
  50. }
Success #stdin #stdout 0s 3412KB
stdin
Standard input is empty
stdout
First catch: Something bad happened
Second catch: std::exception