Description
Given the following multi_throw function, you are asked to write a program to catch all the exceptions. The program first reads an integer, passes it to the multi_throw function,
and catches the exception that it may throw.
void multi_throw(int i)
{ cout << "Input: " << i << endl; if (i <= 0) throw logic_error("non-positive"); if (i <= 1) throw i; if (i <= 5) throw runtime_error("run error"); if (i >= 9) throw out_of_range("too big"); } Your submitted source code should not include the multi_throw function.
Input
Input contains multiple test cases. Each case consists of an integer on a single line. Process to the end of file.
Output
For each test case, ouput the exception message and the type of exception if an exception is catched. Please follow the formats of the sample output.
Sample Input
-1 1 9
Sample Output
Input: -1 Exception: non-positive Exception type: class logic_error Input: 1 Exception: 1 Exception type: int Input: 9 Exception: too big Exception type: class out_of_range |
一發WA:
#include<iostream>
#include<cmath>
#include<stdexcept>
#include<cstring>
#include "string"
#include <stdlib.h>
#include <typeinfo>
using namespace std;
void multi_throw(int i)
{
cout << "Input: " << i << endl;
if (i <= 0) throw logic_error("non-positive");
if (i <= 1) throw i;
if (i <= 5) throw runtime_error("run error");
if (i >= 9) throw out_of_range("too big");
}
int main(){
int s;
cin>>s;
try{
multi_throw(s);
}
catch(logic_error &lx){
cout<<"Exception: "<<lx.what()<<endl;
cout<<"Exception type: class logic_error"<<endl;
}
catch(int ix){
cout<<"Exception: "<<ix<<endl;
cout<<"Exception type: int"<<endl;
}
catch(runtime_error &rx){
cout<<"Exception: "<<rx.what()<<endl;
cout<<"Exception type: class runtime_error"<<endl;
}
catch(out_of_range &ox){
cout<<"Exception: "<<ox.what()<<endl;
cout<<"Exception type: class out_of_range"<<endl;
}
}
AC:文件結束While(cin>>x)以CTRL+Z結束 catch的順序?
#include<iostream>
#include<cmath>
#include<stdexcept>
#include<cstring>
#include "string"
#include <stdlib.h>
#include <typeinfo>
using namespace std;
/*void multi_throw(int i)
{
cout << "Input: " << i << endl;
if (i <= 0) throw logic_error("non-positive");
if (i <= 1) throw i;
if (i <= 5) throw runtime_error("run error");
if (i >= 9) throw out_of_range("too big");
}*/
int main(){
int s;
while(cin>>s){
try{
multi_throw(s);
}
catch(int ix){
cout<<"Exception: "<<ix<<endl;
cout<<"Exception type: int"<<endl;
}
catch(runtime_error &rx){
cout<<"Exception: "<<rx.what()<<endl;
cout<<"Exception type: class runtime_error"<<endl;
}
catch(out_of_range &ox){
cout<<"Exception: "<<ox.what()<<endl;
cout<<"Exception type: class out_of_range"<<endl;
}
catch(logic_error &lx){
cout<<"Exception: "<<lx.what()<<endl;
cout<<"Exception type: class logic_error"<<endl;
}
}
return 0;
}
conclusion: