詳細で特定のエラー情報を提供するために使用できるCでカスタム例外クラスを作成するには、次の手順に従ってください。
std::exception
からの継承:標準Cライブラリは、 std::exception
という基本クラスを提供します。このクラスを継承することにより、カスタム例外クラスには標準のインターフェイスがあります。<code class="cpp">#include <exception> #include <string> class CustomException : public std::exception { private: std::string message; public: CustomException(const std::string& msg) : message(msg) {} // Override what() to return the custom error message const char* what() const noexcept override { return message.c_str(); } };</string></exception></code>
<code class="cpp">class FileException : public std::exception { private: std::string filename; int errorCode; public: FileException(const std::string& file, int errCode) : filename(file), errorCode(errCode) {} const char* what() const noexcept override { return "File operation failed"; } std::string getFilename() const { return filename; } int getErrorCode() const { return errorCode; } };</code>
このFileException
クラスは、ファイルの操作の障害に関連付けられたファイル名とエラーコードを保存し、より詳細なエラーの報告と取り扱いを可能にします。
Cでカスタム例外クラスを使用すると、いくつかの重要な利点があります。
std::exception
から継承されるため、標準ライブラリの例外処理メカニズムとシームレスに統合され、既存のコードとライブラリと互換性があります。Cでのカスタム例外の効果的な取り扱いには、いくつかのベストプラクティスとテクニックが含まれます。
try
ブロック内でカスタム例外をスローする可能性のあるコードを囲み、 catch
ブロックを使用してそれらの例外を適切に処理します。例えば:<code class="cpp">try { // Code that may throw a FileException if (!fileExists("example.txt")) { throw FileException("example.txt", 404); } } catch (const FileException& e) { std::cerr </code>
catch (...)
)に注意してください。それらはいくつかのシナリオで役立つ可能性がありますが、エラーをマスクすることもできます。可能な場合は、常に特定の例外をキャッチすることを好みます。これらのプラクティスに従うことにより、カスタム例外を効果的に処理し、より堅牢で信頼性の高いCアプリケーションにつながることができます。
以上がCでカスタム例外クラスを作成するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。