Not logged in. Log in with GitHub. About Websheets.

List of all available Websheets


Viewing cpp/cs104/exceptions/divide_throw_same_type by redekopp@usc.edu. You have unsaved changes. Log in above to create, edit, preview and publish Websheets.
PropertyValue
Description
html markup
shown to student
 
It is better to throw specific types for each exception case you check for since two cases throwing the same type will be hard to distinguish by the caller?  
Add code such that when the denominator is 0 an exception is thrown and caught in main and then prints <tt>Denom is 0</tt>.  
<p>
Also, add code such that when the numerator is 0 an exception is thrown and caught in main and then prints <tt>Num is 0</tt>.  
<p>
   How could you change the code so that each exception was caught in its own <tt>catch<tt> block?
Remarks
Comments, history, license, etc.
 
Copied from problem cpp/cs104/exceptions/divide_std_except (author: redekopp@usc.edu)
Copied from problem cpp/cs104/exceptions/divide_throw_catch_main (author: redekopp@usc.edu)
Copied from problem cpp/cs104/exceptions/divide_throw_catch_primitive (author: redekopp@usc.edu)
Copied from problem cpp/cs104/exceptions/divide_throw_only (author: redekopp@usc.edu)
Copied from problem cpp/cs104/exceptions/divide_assert (author: redekopp@usc.edu)
Copied from problem cpp/cs104/exceptions/divide1 (author: redekopp@usc.edu)
remove
Engine
Template / Reference solution
 
#include <iostream>
#include <string>
#include <stdexcept>
using namespace std;
struct Num0Error {};
struct Denom0Error {};
int divide(int num, int denom)
{
   if(denom == 0){
\[
REDACTED
\show:
      throw 0;
]\
   }
   else if(num == 0){
\[
REDACTED
\show:
      throw 1;  
]\
   }
   cout << "Normal case" << endl;
   return(num/denom);
}
int main()
{
   int res = -1, n, d;
   cout << "Enter num & denom: " << endl;
   cin >> n >> d;
   // Add code to try and catch exception cases
   //  and if an exception is caught, try to get another
   //  input from the user until they enter a value that
   //  does not generate an exception.
   \[
REDACTED
\show:
      try {
         res = divide(n, d);
         // I'll only get here if no exception occurred
      }
      catch(int  val){
         // Why did we fail?  We'd have to look at the thrown value
         // and somehow interpret it to find the root cause if we
         // wanted to fix it.
         cout << val << endl;  
      }
   ]\
   cout << res << endl;
   return 0;
}
C++ test suite
json list of stdin/args tests
e.g. [{"stdin":"hi", "args":["4", "5"]},
{"stdin":"noargs"}]

to just run once with no input use [{}]
 
[{"stdin":"0 4"}, {"stdin":"4 0"}, {"stdin":"4 2"}  ]
Solution visibility remove


Optional properties:

Note: problems are open-source by default (see 'Public permissions'). Assumed license for open problems is Creative Commons 4.0 Attribution-ShareAlike unless specified in 'Remarks'.