• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 186
  • Last Modified:

Exception Handling in C++

I have to write an exception class that will output a different message for each different situation, how do I even start writing an exception class. Please help. Thanks

mb
0
mb650cd
Asked:
mb650cd
  • 2
1 Solution
 
PerlChaserCommented:
You can create an exception class by simply using a message in it.  For example, if you were checking for invalid digits, you would use

InvalidDigit::InvalidDigit()
{ msg = "That is not a valid digit.\n"; }

Then, in your code you could have

if(!(isdigit(n)))
  throw InvalidDigit();

Hope this helps!
~PerlChaser~
0
 
n_fortynineCommented:
for ex:

class Exception {
   string  msg;
  public:
   Exception(string mesg) : msg(mesg) {}
   const string what() { return msg; }
};

then throw it as PerlChaser said when you write your code (1). You then use a try-catch (or try-catch-catch-...-finally) block when writing codes that use the code (1).

code:
void Check(int n) {
 // borrow code from PerlChaser
}

then:
try {
 Check('a');
}
catch (Exception ex) {
   cout << ex.what() << "\n";
}

something like that. =)
0
 
PerlChaserCommented:
mb650cd,

Please wrap up this question; you have had sufficient time to evaluate these comments.
0
 
tinchosCommented:
No comment has been added lately, so it's time to clean up this TA.
I will leave a recommendation in the Cleanup topic area that this question is:

Answered by: n_fortynine

Please leave any comments here within the next seven days.

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!

Tinchos
EE Cleanup Volunteer
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now