# Catching Errors

In this example we ask the user to enter the date as mm/dd/year.

We need to check for lots of errors. The slash could be missing, the conversion from string to int could fail, and then it could still be an invalid date.

Since there will be three integers to convert, it is easier to write a function and write the try/catch block just once. Since we know that month, day, and year must all be positive, we return -1 as a signal that the conversion failed.

 `123456789101112131415161718192021222324252627282930313233343536373839404142` ```#include #include using namespace std; int getInteger(string s) { int result=-1; try { result=stoi(s); } catch(invalid_argument&) { //do nothing, result is still -1 } return result; }//getInteger int main(void) { string input; int month,day,year; cout<<"Enter the date as mm/dd/year:"; cin>>input; //Example: 10/31/2016 int p=input.find_first_of("/"); // Using example: p=2 if(p<0) cout<<"not a valid date\n"; else { month=getInteger(input.substr(0,p)); //Using example: month=10 input=input.substr(p+1); //Using example: input="31/2016" p=input.find_first_of("/"); //Using example: p=2 day=getInteger(input.substr(0,p)); //Using example: day=31 input=input.substr(p+1); //Using example: input="2016" year=getInteger(input); //Using example: year=2016 if(month<0 || month>12 || day<0 || day>31 || year<0) cout<<"not a valid date\n"; else { //We have 3 integers, it still might not be a valid date! int days[]={0,31,28,31,30,31,30,31,31,30,31,30,31}; string months[]={"","January","February","March","April","May","June", "July","August","September","October","November","December"}; if(day>days[month]) cout<<"There are not that many days in "<
CODE