+ 1
Write a program to take input from user and check whether greater than zero , Less than zero , and Zero . Using try catch throw
#include<iostream> using namespace std; int test(int x){ try{ int y , int z; if (x>0) throw x ; else if (x<0) throw y ; else throw z ; } catch (int x){ cout<<" Less than zero "; } catch (int y) { cout<<"Greater than zero "; } catch (int z) { cout<<" Zero "; } return 0; } int main () { int a ; cout<<"Enter any number "<<endl; cin>>a; test(a); return 0; }
5 odpowiedzi
+ 2
Well, you can throw certain value, catch and return it to the caller. This is ridiculous though 😁
#include<iostream>
int test( int x )
{
try
{
if ( x > 0 )
throw 1;
else if ( x < 0 )
throw -1;
else
throw 0;
}
catch ( int ex )
{
return ex;
}
}
int main ()
{
int a;
const char* status[ 3 ] { "Less than zero", "Zero", "Greater than zero" };
std::cin >> a;
std::cout << status[ test( a ) + 1 ];
return 0;
}
+ 2
Hello problem is solved
Can you explain
Why you use
const char* status[ 3 ] { "Less than zero", "Zero", "Greater than zero" };
+ 2
It's an array, and we get the desired element index by adding 1 to the return value of function `test`.
When `test` returns
-1 => -1 + 1 = 0
index 0 -> "Less than zero"
0 => 0 + 1 = 1
index 1 -> "Zero"
1 => 1 + 1 = 2
index 2 -> "Greater than zero"
0
You do know that you can achieve this by using conditionals right?
0
Ipang I know but I need to complete using try catch & throw