Você está na página 1de 7

Exception Handling

Exceptions
Exceptions are error that occur at run time There may be many reasons for occurrence of exceptions Falling short of memory Inability to open a file Exceeding the bounds of an array Attempting to initialize an object to an impossible value

When exceptions occur.


The programmer has to decide a strategy according to which he would handle the exceptions Displaying the error messages on the screen Displaying a dialog box in case of a GUI environment, or requesting the user to supply better data

Old way for handling Exceptions


If( func1()==ERROR_VALUE) // handle the error Else // do normal things
If( func2()==NULL) // handle the error Else // do normal things

Three problems with this approach


Every time we call a function we must check its return value through a pair of if and else. Surrounding every function call with a pair of if and else results in increase in code size. Also result in less readability This approach cannot be used with constructors of a class as the constructors cannot return a value It becomes difficult to monitor the return values in case of deeply nested function calls

Exception Handling in C++


C++ provides a systematic, oo approach to handling run-time errors generated by C++ classes The exception handling of C++ uses three new keywords: throw, catch, and try. Also, we need to create a new entity called exception class

Example
class sample { public: // exception class class errorclass { }; void fun() { if( some error occurs) throw errorclass(); // throws exception } }; // application void main() { // try block try { Sample s; s.fun(); } catch( sample:errorclass) // exception handler or catch block { // do something about the error cout<< You are Idiot; }

Você também pode gostar