exception handling in c++ (1)
exception handling in c++ (1)
// exceptions
#include <iostream.h>
int main () {
char myarray[10];
try
{
for (int n=0; n<=10; n++)
{
if (n>9) throw "Out of range";
myarray[n]='z';
}
}
int main () {
try
{
char * mystring;
mystring = new char [10];
if (mystring == NULL) throw "Allocation failure";
for (int n=0; n<=100; n++)
{
if (n>9) throw n;
mystring[n]='z';
}
}
catch (int i)
{
cout << "Exception: ";
cout << "index " << i << " is out of range" << endl;
}
catch (char * str)
{
cout << "Exception: " << str << endl;
}
return 0;
}
exception
bad_alloc:(thrown by new)
bad_cast:(thrown by dynamic_cast when fails with a referenced type)
bad_exception:(thrown when an exception doesn't match any catch)
bad_typeid:(thrown by typeid)
logic_error:
domain_error:
invalid_argument:
length_error:
out_of_range:
runtime_error:
overflow_error:
range_error:
underflow_error:
ios_base::failure:(thrown by ios::clear)
Because this is a class hierarchy, if you include a catch block to capture any of the exceptions of this hierarchy using the argument by reference
(i.e. adding an ampersand & after the type) you will also capture all the derived ones (rules of inheritance in C++).
The following example catches an exception of type bad_typeid (derived from exception) that is generated when requesting information about
the type pointed by a null pointer:
// standard exceptions
#include <iostream.h>
#include <exception>
#include <typeinfo>
int main () {
try {
A * a = NULL;
typeid (*a);
}
catch (std::exception& e)
{
cout << "Exception: " << e.what();
}
return 0;
}
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
class Date
{
private:
int mo, da, yr;
public:
Date()
{
mo=da=yr=0;
}
Date(int m, int d, int y)
{
mo = m; da = d; yr = y;
}
friend ostream& operator<<(ostream& , const Date& );
friend istream& operator>>(istream& , Date& );
};
main()
{
clrscr();
Date dt;
cin>>dt;
cout<<dt;
getch();
}