Showing posts with label Exception. Show all posts
Showing posts with label Exception. Show all posts

Sunday, January 8, 2012

Exception Part 2(Example)





Running Codes
// exceptions_Exception_Examples.cpp
// compile with: /EHsc
#include

using namespace std;
void MyFunc( void );

class CTest
{
public:
CTest(){};
~CTest(){};
const char *ShowReason() const { return "Exception in CTest class."; }

};

class CDtorDemo
{
public:
CDtorDemo();
~CDtorDemo();
};

CDtorDemo::CDtorDemo()
{
cout << "Constructing CDtorDemo." << endl;
}

CDtorDemo::~CDtorDemo()
{
cout << "Destructing CDtorDemo." << endl;
}

void MyFunc()
{

CDtorDemo D;
cout<< "In MyFunc(). Throwing CTest exception." << endl;
throw CTest();
}

int main()
{
cout << "In main." << endl;
try
{
cout << "In try block, calling MyFunc()." << endl;
MyFunc();
}
catch( CTest E )
{
cout << "In catch handler." << endl;
cout << "Caught CTest exception type: ";
cout << E.ShowReason() << endl;
}
catch( char *str )
{
cout << "Caught some other exception: " << str << endl;
}
cout << "Back in main. Execution resumes here." << endl;
return 0;
}
http://www.cprogramming.com/tutorial/exceptions.html

Exception Part1




Exceptions are run time anomalies or unusual
conditions that a program may encounter during
execution.
Conditions such as
*Division by zero Division by zero
*Access to an array outside of its bounds
*Running out of memory
*Running out of disk space
It was not a part of original C++.
It is a new feature added to ANSI C++.

Exceptions are of 2 kinds
1.Synchronous Exception:
Out of rage
Over flow
2.Asynchronous Exception: Error that are caused by
causes beyond the control of the program
Keyboard interrupts
In C++ only synchronous exception can be
handled.
Exception handling mechanism
Find the problem (Hit the exception)
Inform that an error has occurred (Throw the exception) Inform that an error has occurred (Throw the exception)
Receive the error information (Catch the exception)
Take corrective action (handle the exception)
EXCEPTION HANDLING MECHANISM

It is basically build
upon three keywords
Try
Throw
Catch
try block Detects and throws an exception
Catch
catch block
Catch

The keyword tryis used to preface a block of
statements which may generate exceptions.
When an exception is detected, it is thrown using a
throwstatement in the try block. throwstatement in the try block.
A catchblock defined by the keyword ‘catch’
catches the exception and handles it appropriately.
The catch block that catches an exception must
immediately follow the try block that throws the
exception.
EXCEPTIONHANDLINGMECHANISM(CONT…)
try
{

throw exception;

// Block of statements
// which detect and
// throws an exception …
}
catch(type arg)
{



}
// throws an exception
// catch exception
// Block of statement
// that handles the
// exception
Running Codes
http://www.cprogramming.com/tutorial/exceptions.html