Exception Handling Handling an unexpected behaviour Unit - 08.
-
Upload
sergio-ashbridge -
Category
Documents
-
view
232 -
download
0
Transcript of Exception Handling Handling an unexpected behaviour Unit - 08.
Exception Exception HandlingHandling
Handling an unexpected Handling an unexpected behaviourbehaviour
Unit - 08Unit - 08
Unit IntroductionUnit Introduction
This unit covers C++ exception This unit covers C++ exception handling mechanismhandling mechanism
Unit ObjectivesUnit Objectives
After covering this unit you will After covering this unit you will understand…understand…
Exception handlingException handling Throwing exceptionsThrowing exceptions Catching an exceptionCatching an exception Termination vs. ResumptionTermination vs. Resumption Exception specificationException specification Uncaught exceptionUncaught exception Exception objectsException objects
Exception HandlingException Handling
To recover from undesirable To recover from undesirable situationsituation
To increase robustness of codeTo increase robustness of code Deal with synchronous errorsDeal with synchronous errors Recovery procedure as exception Recovery procedure as exception
handlerhandler
Throwing an ExceptionThrowing an Exception
Throwing an exception as raising an Throwing an exception as raising an exceptionexception
We can specify the exceptions a We can specify the exceptions a function throwsfunction throws
Point at which throw is executed, is Point at which throw is executed, is called throw pointcalled throw point
Use of throw keywordUse of throw keywordthrow MyException(“This is My Exception”); throw MyException(“This is My Exception”);
Re-throwing an Re-throwing an ExceptionException
In catch block, an exception caught In catch block, an exception caught can be re-thrown to a higher level can be re-thrown to a higher level using using throwthrow
throw statement should appear in a throw statement should appear in a catch handler otherwise it will cause catch handler otherwise it will cause a call to terminatea call to terminate
catch(...) catch(...) // catching any general exception// catching any general exception
{ {
cout << ”An Exception occurred”;cout << ”An Exception occurred”;
throw; throw; // re-throwing an exception// re-throwing an exception
}}
Catching an ExceptionCatching an Exception
Use of try and catch keywordUse of try and catch keyword To solve the problem within same To solve the problem within same
scopescope catch blocks, as exception handlerscatch blocks, as exception handlers Only one exception handler for every Only one exception handler for every
exception type exception type try try
{{ // code that may generate exceptions// code that may generate exceptions
} }
catch(ExceptionType1 id1) // specific typecatch(ExceptionType1 id1) // specific type
{ { // to handle exceptions of type1// to handle exceptions of type1
} }
catch(...) // general exceptioncatch(...) // general exception
{ { // to handle any general exception// to handle any general exception
}}
Catching an Exception Catching an Exception (contd.)(contd.)
Enclose the code in Enclose the code in trytry block that can block that can throw an exceptionthrow an exception
For a try block place one or more For a try block place one or more catchcatch blocks blocks
In each catch block catch the In each catch block catch the required exception that need to be required exception that need to be caughtcaught
Catching (…) means any exception Catching (…) means any exception will be caughtwill be caught
Termination vs. Termination vs. ResumptionResumption
Two models in exception handling Two models in exception handling theorytheory
Unrecoverable error cause Unrecoverable error cause terminationtermination
To resume program execution after To resume program execution after recovering form error is resumptionrecovering form error is resumption
Example: Exception Example: Exception HandlingHandlingclass BaseException class BaseException
{ {
public: public:
BaseException() { m_pError = “Base Exception”; }BaseException() { m_pError = “Base Exception”; }
void PrintError() const { cout << m_pError; }void PrintError() const { cout << m_pError; }
char* m_pError; char* m_pError;
}; };
class DerivedException : public BaseException class DerivedException : public BaseException
{ {
public:public:
DerivedException() {m_pError = “Derived Exception”; }DerivedException() {m_pError = “Derived Exception”; }
};};
float quotient(int num1, int num2) float quotient(int num1, int num2)
{{
if(num1 == 0 && num2 == 0)if(num1 == 0 && num2 == 0)
throw BaseException();throw BaseException();
else if(num2 == 0)else if(num2 == 0)
throw DerivedException();throw DerivedException();
Example: Exception Handling Example: Exception Handling (contd.)(contd.)
return (float) num1 / num2;return (float) num1 / num2; // normal flow of execution// normal flow of execution
}}
void main()void main()
{ {
try try
{{
try try
{{
float result = quotient(5, 0);float result = quotient(5, 0);
cout << “Quotient is:” << result;cout << “Quotient is:” << result;
throw 1; throw 1; //throwing primitive type exception//throwing primitive type exception
} }
catch(DerivedException exception) catch(DerivedException exception)
{ {
exception.printError();exception.printError();
} }
Example: Exception Handling Example: Exception Handling (contd.)(contd.)
catch(BaseException exception) catch(BaseException exception)
{{
exception.printError();exception.printError();
} catch(...) } catch(...)
{ {
cout << ”General exception”;cout << ”General exception”;
throw; throw; // re-throwing an exception// re-throwing an exception
}}
} }
catch(...) catch(...)
{{
cout << “General exception again occurred”;cout << “General exception again occurred”;
}}
}}
Exception SpecificationException Specification
Enables a list of exceptions that can be Enables a list of exceptions that can be thrown by a function to be specifiedthrown by a function to be specified
Exception specification is also called Exception specification is also called throw listthrow list
throwthrow clause is used in function clause is used in function signaturesignature void Function() throw(DivByZero, void Function() throw(DivByZero,
IllegalNumber);IllegalNumber); void Function();void Function(); void Function() throw;void Function() throw;
Exception Specification Exception Specification (contd.)(contd.) unexpected()unexpected() is called if an is called if an
exception is thrown that is not in exception is thrown that is not in exception specification which by exception specification which by default calls default calls terminate()terminate()
A user function can be specified A user function can be specified when unexpected() is called by when unexpected() is called by set_unexpectedset_unexpected function function
abort()abort() will automatically be will automatically be called after the last action of user-called after the last action of user-defined termination functiondefined termination function
Example: Exception Example: Exception SpecificationSpecification
class Exception1 {};class Exception1 {};
class Exception2 {};class Exception2 {};
void UnexpectedException();void UnexpectedException();
void Function(int i) throw (Exception1, Exception2) void Function(int i) throw (Exception1, Exception2)
{{
switch(i) switch(i)
{{
case 1:case 1: throw Exception1();throw Exception1();
case 2:case 2: throw Exception2();throw Exception2();
}}
UnexpectedException(); UnexpectedException(); // calls unexpected function// calls unexpected function
}}
void UnexpectedException() { throw 1; }void UnexpectedException() { throw 1; }
void MyTerminationFunction() void MyTerminationFunction()
{{ cout << “unexpected exception occurred”; }cout << “unexpected exception occurred”; }
Example: Exception Specification Example: Exception Specification (contd.)(contd.)
void main()void main()
{{
set_unexpected(MyTerminationFunction);set_unexpected(MyTerminationFunction);
// ignores return value// ignores return value
for(int i = 1; i <=3; i++)for(int i = 1; i <=3; i++)
try try
{{
function(i);function(i);
} }
catch(Exception1) catch(Exception1)
{{
cout << "Exception1 occurred";cout << "Exception1 occurred";
} }
catch(Exception2) catch(Exception2)
{{
cout << "Exception2 occurred";cout << "Exception2 occurred";
}}
}}
Uncaught ExceptionUncaught Exception
If an exception occurs that has no If an exception occurs that has no matching catch block, matching catch block, terminate()terminate() is calledis called
terminate()terminate() is a pointer to function, is a pointer to function, by default this function is by default this function is abort()abort()
set_terminate()set_terminate() can be used to set can be used to set a user defined function, when a user defined function, when terminate() will be calledterminate() will be called
Example: Uncaught Example: Uncaught ExceptionException
void MyTerminate() void MyTerminate()
{{
cout << "My terminate";cout << "My terminate";
abort(); abort(); // must be aborted// must be aborted
}}
void (*ptr_fn)()= set_terminate(MyTerminate); void (*ptr_fn)()= set_terminate(MyTerminate); //ptr to fn//ptr to fn
class Outer class Outer
{{
public:public:
class Inner {};class Inner {};
void Function() void Function()
{{
cout << "Outer::function()";cout << "Outer::function()";
throw Inner(); throw Inner();
}}
};};
Example: Uncaught Exception Example: Uncaught Exception (contd.)(contd.)
void main() void main()
{{
try try
{{
Outer obj;Outer obj;
obj.Function();obj.Function(); // results in call to terminate // results in call to terminate
// function// function
} }
catch(Outer) catch(Outer)
{{
cout << "trying to catch outer exception";cout << "trying to catch outer exception";
}}
// no handler for Inner type exception// no handler for Inner type exception
}}
Exception ObjectsException Objects
Exception to be caught can be as Exception to be caught can be as simple as an simple as an intint and as complex as a and as complex as a complete class typecomplete class type
Exception object should be caught Exception object should be caught by reference, and not by valueby reference, and not by value
Exception can also be caught as a Exception can also be caught as a pointerpointer
Example: Catch By Example: Catch By ReferenceReference
class Parent class Parent
{{
public:public:
virtual void Print() virtual void Print()
{{
cout << "Parent";cout << "Parent";
}}
};};
class Child : public Parent class Child : public Parent
{{
public:public:
void Print() { cout << "Child"; }void Print() { cout << "Child"; }
};};
void Function() { throw Child(); }void Function() { throw Child(); }
// function throwing exception of type Child// function throwing exception of type Child
Example: Catch By Reference Example: Catch By Reference (contd.)(contd.)
int main() int main()
{{
try try
{{
Function();Function();
} }
catch(Parent p) catch(Parent p) // catch by value, child object sliced// catch by value, child object sliced
{ {
p.Print();p.Print();
}}
try try
{{
Function();Function();
} }
catch(Parent& p) catch(Parent& p) //catch by reference//catch by reference
{ {
p.Print();p.Print();
}}
}}
Unit SummaryUnit Summary
In this unit you have covered …In this unit you have covered … Handling of exceptionsHandling of exceptions Throwing exceptionsThrowing exceptions Catching an exceptionCatching an exception Exception specificationException specification Uncaught exceptionUncaught exception Exception objectsException objects