Custom Exception Types and Declarations in C++

declaring a custom exception type n.w
1 / 4
Embed
Share

Learn how to declare custom exception types in C++, including creating custom exception classes like MyException, nesting exception declarations, and creating useful base classes for handling errors effectively in your C++ code.

  • C++
  • Exception handling
  • Custom exception
  • Base classes
  • Error handling

Uploaded on | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.

E N D

Presentation Transcript


  1. Declaring a Custom Exception Type class MyException : public std::exception { public: MyException(const std::string& msg) : message(msg) {} const char *what() const noexcept { return message.c_str(); } private: std::string message; }; CS 190 Lecture Notes: Code Review 2 Slide 1

  2. Nest Exception Declarations Wrong: Right: class PersistentStorageFailure : public std::exception { ... }; class PersistentStorage { public: class StorageFailure : public std::exception { ... }; ... }; class PersistentStorage { ... }; throw PersistentStorageFailure( storage corrupted ); throw PeristentStorage::StorageFailure( storage corrupted ); CS 190 Lecture Notes: Code Review 2 Slide 2

  3. Create Useful Base Classes class ExceptionWithErrno : public std::exception { public: ExceptionWithErrno(const std::string& msg) { message = msg + ": " + strerror(errno); } const char *what() const noexcept { return message.c_str(); } private: std::string message; }; class StorageError : public ExceptionWithErrno { public: StorageError(const std::string& msg) : ExceptionWithErrno(msg) {} } CS 190 Lecture Notes: Code Review 2 Slide 3

  4. Another Useful Base Class class ExceptionWithPrintf : public std::exception { public: ExceptionWithPrintf(const char *format, ...) { char buffer[1000]; va_list args; va_start(args, format); vsnprintf(buffer, sizeof(buffer), format, args); message = buffer; } const char *what() const noexcept { return message.c_str(); } private: std::string message; }; throw ExceptionWithPrintf( Couldn t bind to port %d: %s , portNum, strerror(errno)); CS 190 Lecture Notes: Code Review 2 Slide 4

Related


More Related Content