| | |
Exceptions (repost)
![]() |
•
•
Join Date: Sep 2006
Posts: 38
Reputation:
Solved Threads: 1
Exceptions
--------------------------------------------------------------------------------
I am working on a class project as layed out by the instructor. This is in conjunction with Chapter 13 (Exceptions) from the book How To Program in C++ by Deitle 4/e. I am at a total loss on this subject. I thought that catching problems was up to the compiler. I have included Figure 13.1 for an example as per instructions and some code I have been working on. Could someone please look this over and help me get my brain around exceptions or at least this project?
// Fig. 13.1: fig13_01.cpp
// A simple exception-handling example that checks for
// divide-by-zero exceptions.
Here is the instructions and code I'm trying to use.
/*Create a program that defines three user defined exception classes
(called ExceptionOne, ExceptionTwo, and ExceptionThree
- with the messages being the same as the name - see Figure 13.1 for an example).
The program should have a loop with a menu with four selections
- Option 1 will throw ExceptionOne, Option 2 ExceptionTwo, Option 3 ExceptionThree
, and Option 4 to exit.
The catch block should only catch the first two exceptions explicitly
with the last exception caught generically.
Make sure the switch logic is inside a try block followed by three catch blocks.
///////////////////////////////////////////////////////////////////////////////
Any help greatly appreciated. Thanks
--------------------------------------------------------------------------------
I am working on a class project as layed out by the instructor. This is in conjunction with Chapter 13 (Exceptions) from the book How To Program in C++ by Deitle 4/e. I am at a total loss on this subject. I thought that catching problems was up to the compiler. I have included Figure 13.1 for an example as per instructions and some code I have been working on. Could someone please look this over and help me get my brain around exceptions or at least this project?
// Fig. 13.1: fig13_01.cpp
// A simple exception-handling example that checks for
// divide-by-zero exceptions.
C++ Syntax (Toggle Plain Text)
#include <iostream> using std::cout; using std::cin; using std::endl; #include <exception> using std::exception; // DivideByZeroException objects should be thrown by functions // upon detecting division-by-zero exceptions class DivideByZeroException : public exception { public: // constructor specifies default error message DivideByZeroException::DivideByZeroException() : exception( "attempted to divide by zero" ) {} }; // end class DivideByZeroException // perform division and throw DivideByZeroException object if // divide-by-zero exception occurs double quotient( int numerator, int denominator ) { // throw DivideByZeroException if trying to divide by zero if ( denominator == 0 ) throw DivideByZeroException(); // terminate function // return division result return static_cast< double >( numerator ) / denominator; } // end function quotient int main() { int number1; // user-specified numerator int number2; // user-specified denominator double result; // result of division cout << "Enter two integers (end-of-file to end): "; // enable user to enter two integers to divide while ( cin >> number1 >> number2 ) { // try block contains code that might throw exception // and code that should not execute if an exception occurs try { result = quotient( number1, number2 ); cout << "The quotient is: " << result << endl; } // end try // exception handler handles a divide-by-zero exception catch ( DivideByZeroException ÷ByZeroException ) { cout << "Exception occurred: " << divideByZeroException.what() << endl; } // end catch cout << "\nEnter two integers (end-of-file to end): "; } // end while cout << endl; return 0; // terminate normally } // end main
/*Create a program that defines three user defined exception classes
(called ExceptionOne, ExceptionTwo, and ExceptionThree
- with the messages being the same as the name - see Figure 13.1 for an example).
The program should have a loop with a menu with four selections
- Option 1 will throw ExceptionOne, Option 2 ExceptionTwo, Option 3 ExceptionThree
, and Option 4 to exit.
The catch block should only catch the first two exceptions explicitly
with the last exception caught generically.
Make sure the switch logic is inside a try block followed by three catch blocks.
///////////////////////////////////////////////////////////////////////////////
C++ Syntax (Toggle Plain Text)
#include <iostream> #include <exception> #include <ctime> using std::cout; using std::cin; using std::endl; class BaseException { public: // constructor specifies default error message ExceptionOne::BaseException () : ExceptionOne }// end class class ExceptionOne: public BaseException { public: ExceptionOne::ExceptionOne() :ExceptionOne }// end class class ExceptionTwo: public ExceptionOne { public: // constructor specifies default error message ExceptionTwo::ExceptionTwo() : ExceptionTwo } // end class class ExceptionThree: public ExceptionTwo { public: ExceptionThree::ExceptionThree() :ExceptionThree }// end class int main() {
Any help greatly appreciated. Thanks
Please use proper indentation for your code. Doing it is a good habit, and most editors have an option that enables automatic indentation. That way we can read your code eaiser. 
>I thought that catching problems was up to the compiler.
It is, but not entirely. A compiler can only catch syntax errors, not runtime errors. For example, consider the following equation:
Now, most compilers will automatically alert you of this error because of course, you cannot divide by 0. This is a syntax error. However, consider this statement:
The compiler has no way of knowing what
That's where exception handling comes in. It allows you an easy way to control and handle errors, as opposed to the traditional C-style of error checking, where you decided a function's success purely based on return code or values of pointers modified.
You could just throw a simple string, but using classes gives you much more flexibility. You can fill in data such as where the error occured, the date and time, why it occured. Additionally, using classes allows you to take advantage of exception handling's type checking, which will automatically pick out the right catch block to use.

>I thought that catching problems was up to the compiler.
It is, but not entirely. A compiler can only catch syntax errors, not runtime errors. For example, consider the following equation:
C++ Syntax (Toggle Plain Text)
x=5/0;
C++ Syntax (Toggle Plain Text)
x=5/divider;
divider will contain at runtime. It could have been inputted by the user, been generated as a random number, etc.. There's many other runtime errors that the compiler cannot predict, such as the computer having insufficient memory, a file being missing; you get the idea. So then it's up to your program to handle the errors.That's where exception handling comes in. It allows you an easy way to control and handle errors, as opposed to the traditional C-style of error checking, where you decided a function's success purely based on return code or values of pointers modified.
You could just throw a simple string, but using classes gives you much more flexibility. You can fill in data such as where the error occured, the date and time, why it occured. Additionally, using classes allows you to take advantage of exception handling's type checking, which will automatically pick out the right catch block to use.
"Technological progress is like an axe in the hands of a pathological criminal."
![]() |
Similar Threads
- Exceptions (C++)
- weird exceptions:( (Python)
- How to handle exceptions in constructor? (Java)
- repost: leak using c++ string (C++)
- Exceptions (Java)
- Arithmetic Exceptions and exception-handling statements (Java)
Other Threads in the C++ Forum
- Previous Thread: Solve a 2x2 linear equation matrix with Cramer's Rule
- Next Thread: Game engine
| Thread Tools | Search this Thread |
api array based binary bitmap business c++ c/c++ char class classes code coding commentinghelp compile console conversion count decide delete deploy desktop developer directshow dll download dynamic dynamiccharacterarray email encryption error file forms fstream function functions game givemetehcodez graph guess gui homeworkhelp homeworkhelper iamthwee ifpug ifstream incrementoperators infinite input int integer java lib linkedlist linker loop looping loops map math matrix memory multiple news node number numbertoword output parameter pointer problem proficiency program programming project python random read recursion reference rpg string strings temperature template templates test text text-file tree url variable vector video win32 windows winsock word wordfrequency wxwidgets






