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

List of all available Websheets


Viewing cpp/cs104/exceptions/divide_rethrow 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
 
An exception can be caught by one function which can check if it can do anything about the problem and if not, it can re-throw the exception by simply writing:
<pre>
throw;
</pre>
in a <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;
int divide(int num, int denom)
{
   if(denom == 0){
      throw std::invalid_argument("Denom is 0");
   }
   cout << "Normal case" << endl;
   return(num/denom);
}
int f1(int x)
{
   try {
      return divide(x, x-2);       
   }
   catch(std::invalid_argument& e){
      // assume code that checks if it can do anything
      cout << "Oops, I'm not the root cause." << endl;
      cout << "Let's throw it up the stack again" << endl;
      throw;  // throw's e again
   }
}
int main()
{
   int res = -1, a;
   cout << "Enter: " << endl;
   cin >> a;
   
   while(true){
      try {
        res = f1(a);
        // I'll only get here if no exception occurred
        break;
      }
    catch(std::invalid_argument& e ){
        cout << e.what() << endl;  
        cout << "\nTrying again" << endl;
        cin >> a;
      }
   }
   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":"2 4"} ]
Solution visibility remove
Is example?
i.e., just a demo
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'.