Note that there are some explanatory texts on larger screens.

plurals
  1. POUsage of throw keyword
    text
    copied!<p>I've recently started coding in C++ and i'm having doubts about the following code. I'm having trouble with the 'throw' keyword. In the median or grade function when will it give an error? What is the exact usage of throw and domain_error? Will i ever get the error message from the grade or median function?</p> <pre><code>#include&lt;iostream&gt; #include&lt;string&gt; #include&lt;vector&gt; #include&lt;iomanip&gt; #include&lt;ios&gt; #include&lt;algorithm&gt; #include&lt;stdexcept&gt; using std::cout; using std::cin; using std::vector; using std::endl; using std::string; using std::streamsize; using std::setprecision; using std::domain_error; using std::istream; double grade(double midterm, double final, double homework) { return 0.2*midterm+0.4*final+0.4*homework; } double median(vector&lt;double&gt; vec) { typedef vector&lt;double&gt;::size_type vec_sz; vec_sz size= vec.size(); if(size==0) { throw domain_error("Median of an empty vector"); //when will i get this error msg?? } sort(vec.begin(),vec.end()); vec_sz mid=size/2; return size%2==0?(vec[mid]+vec[mid-1])/2:vec[mid]; } double grade(double midterm, double final, const vector&lt;double&gt;&amp; hw) { if(hw.size()==0) { throw domain_error("Student has done no homework");// when will i get this error? } return grade(midterm, final, median(hw)); } istream&amp; read_hw(istream&amp; in, vector&lt;double&gt;&amp; hw) { if(in) { hw.clear(); double x; while(in&gt;&gt;x) hw.push_back(x); in.clear(); } return in; } int main() { string name; cout&lt;&lt;"Please enter your name:"; cin&gt;&gt;name; cout&lt;&lt;"Hello "&lt;&lt;name&lt;&lt;"!"&lt;&lt;endl; cout &lt;&lt; "Please enter your midterm and final exam grades: "; double midterm, final; cin &gt;&gt; midterm &gt;&gt; final; cout &lt;&lt; "Enter all your homework grades, " "followed by end-of-file: "; vector&lt;double&gt; homework; read_hw(cin, homework); try { double final_grade = grade(midterm, final, homework); streamsize prec = cout.precision(); cout &lt;&lt; "Your final grade is " &lt;&lt; setprecision(3) &lt;&lt; final_grade &lt;&lt; setprecision(prec) &lt;&lt; endl; } catch (domain_error) { cout &lt;&lt; endl &lt;&lt; "You must enter your grades. " "Please try again." &lt;&lt; endl; return 1; } return 0; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload