12,966
回編集
(→概要) |
|||
111行目: | 111行目: | ||
{ | { | ||
throw *this; | throw *this; | ||
} | |||
</syntaxhighlight> | |||
<br><br> | |||
== QExceptionの使用例 : 0除算 == | |||
以下の例では、QExceptionクラスを継承して、0除算で例外をスローするクラスを定義している。<br> | |||
また、safeDivide関数を定義して、0で除算した場合に、QDivideByZeroExceptionをスローする例を示している。<br> | |||
<br> | |||
このクラスは、以下に示すような特徴を持つ。<br> | |||
* コンストラクタでエラーメッセージを受け取る。 (デフォルトのメッセージもある) | |||
* raiseメソッドをオーバーライドして、例外を再スローできる。 | |||
* cloneメソッドをオーバーライドして、例外オブジェクトの複製を可能にする。 | |||
* whatメソッドをオーバーライドして、エラーメッセージを返す。 | |||
<br> | |||
<syntaxhighlight lang="c++"> | |||
// QDivideByZeroException.hファイル | |||
#include <QCoreApplication> | |||
#include <QException> | |||
class QDivideByZeroException : public QException | |||
{ | |||
private: | |||
QString m_message; | |||
public: | |||
QDivideByZeroException(const QString &message = "Division by zero occurred") : m_message(message) | |||
{} | |||
void raise() const override | |||
{ | |||
throw *this; | |||
} | |||
QDivideByZeroException *clone() const override | |||
{ | |||
return new QDivideByZeroException(*this); | |||
} | |||
const char* what() const noexcept override | |||
{ | |||
return m_message.toLocal8Bit().constData(); | |||
} | |||
}; | |||
</syntaxhighlight> | |||
<br> | |||
<syntaxhighlight lang="c++"> | |||
// main.cppファイル | |||
#include "QDivideByZeroException.h" | |||
double safeDivide(double numerator, double denominator) | |||
{ | |||
if (denominator == 0.0f) { | |||
throw QDivideByZeroException("Attempted to divide by zero"); | |||
} | |||
return numerator / denominator; | |||
} | |||
int main() | |||
{ | |||
try { | |||
double result = safeDivide(10.0, 0.0); | |||
} | |||
catch (const QDivideByZeroException &e) { | |||
qDebug() << "Caught exception:" << e.what(); | |||
} | |||
return 0; | |||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> |