-
February 24th, 2003, 05:27 AM
#1
Member
C++ Exceptions
This is something about exceptions and exception handling in C++.
An exception occurs when we try for an invalid operation. In our code, we will put the code with chance of an illegal operation in a try block. When an illegal operation occurs, it will throw an exception which can be caught by the OS(for that we have to provide exception handling code).
This is a simple divide by zero catcher program.
#include <iostream>
using namespace std;
class Divide
{
public:
class DivideError /*Exception handler class. The constructor is called when throws an exception */
{
};
float divide(int x, int y)
{
if (y == 0)
throw DivideError(); /*Divide by zero is not permitted. So constructor of DivideError class is called */
else
return x/y;
}
};
int main()
{
int x, y;
Divide d;
cout << "Enter 2 numbers : " ;
cin >> x >> y ;
try
{
float f = d.divide(x,y);
cout << f << endl ;
}
catch(Divide:ivideError) /* Works if an exception is thrown from the object */
{
cout << "Division by zero is not possible" << endl ;
}
return 0;
}
-
February 24th, 2003, 05:03 PM
#2
cool post, next time try using [ code ] [ /code ] (with out the spaces)...
that should keep the spaces and make it much easier for us to read?
-take it easy
yeah, I\'m gonna need that by friday...
-
February 26th, 2003, 08:05 AM
#3
Member
When it is not in a class , exceptions are handled this way
Code:
#include <iostream>
using namespace std;
int main()
{
int pid;
char pwd[10] ;
try
{
cout << "Enter login Id : " ;
cin >> pid ;
if (pid != 101)
throw pid;
cout << "Enter password : " ;
cin >> pwd;
if (strcmp(pwd, "abcd") != 0)
throw 'I' ;
}
catch(int)
{
cout << "Invalid login Id" << endl;
}
catch(char str)
{
cout << "Invalid Password" << endl;
}
return 0;
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
|