fork download
  1. #include <iostream>
  2. #include <string>
  3.  
  4. class OpenFileException {
  5. public:
  6. explicit OpenFileException(const std::string& name, int code):
  7. m_name(name),
  8. m_code(code)
  9. {
  10. }
  11.  
  12. std::string name() const
  13. {
  14. return m_name;
  15. }
  16.  
  17. int code() const
  18. {
  19. return m_code;
  20. }
  21.  
  22. private:
  23. std::string m_name;
  24. int m_code;
  25. };
  26.  
  27. void openfile(const std::string& name)
  28. {
  29. if (name == "fail") {
  30. throw OpenFileException(name, 10);
  31. }
  32. }
  33.  
  34. void handlefiles()
  35. {
  36. openfile("/home/Knjagskij/file1.txt");
  37. openfile("/etc/passwd");
  38. openfile("fail"); // Oooops...
  39. openfile("/etc/hosts");
  40. }
  41.  
  42. int main() {
  43. try {
  44. handlefiles();
  45. } catch (const OpenFileException& ex) {
  46. std::cout << "Unable to open file: " << ex.name() << " because of " << ex.code() << std::endl;
  47. }
  48.  
  49. return 0;
  50. }
Success #stdin #stdout 0s 3464KB
stdin
Standard input is empty
stdout
Unable to open file: fail because of 10