SlideShare a Scribd company logo
1 of 19
Exception Handling
Exception Handling
• General mechanism for handling abnormal conditions
• Predefined exceptions: Constraint violations, I/O errors, other
illegalities
• User-defined exceptions
• Exception handlers specify remedial actions or proper
shutdown.
• Exception handling (EH) allows a programmer to provide code
in the program to handle run-time errors or exceptional
situations
– this improves reliability
EXCEPTIONS
Exceptions are run time anomalies or unusual
conditions that a program may encounter during
execution. Conditions such as
• 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++.
EXCEPTION HANDLING
• Exceptions are of 2 kinds
– Synchronous Exception:
• Out of rage
• Over flow
• 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)
• Receive the error information (Catch the
exception)
• Take corrective action (handle the exception)
• It is basically build upon three keywords
– Try
– Throw
– Catch
Example
#include <iostream>
using namespace std;
int main ()
{
try
{
throw 10;
}
catch (int e)
{
cout << “We have a problem!!” << endl;
}
return 0;
}
Output : We have a problem!!!
Contd.
• The keyword try is used to preface a block of
statements which may generate exceptions.
• When an exception is detected, it is thrown using
a throw statement in the try block.
• A catch block 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.
Contd.
• Exceptions are objects used to transmit
information about a problem.
• If the type of the object thrown matches the arg
type in the catch statement, the catch block is
executed.
• If they do not match, the program is aborted
• Often, Exceptions are thrown by functions that
are invoked from within the try blocks.
• The point at which the throw is executed is called
the throw point.
• Once an exception is thrown to the catch block,
control cannot return to the throw point.
THROWING MECHANISM
• The throw statement can have one of the following 3
forms
– throw(exception)
– throw exception
– throw //used to re-throw a exception
• The operand object exception can be of any type,
including constant.
• It is also possible to throw an object not intended for
error handling.
• Throw point can be in a deeply nested scope within a
try block or in a deeply nested function call.
• In any case, control is transferred to the catch
statement
THROWING MECHANISM
• The throw expression accepts one parameter as its argument
and this is passed to the exception handler.
• You can have a number of throw statements at different parts
of your try block with different values being thrown
try
{ // code
if ( x )
throw 10;
// code
if (y)
throw 20;
//code
}
CATCHING MECHANISM
• The type indicates the type of exception the catch block handles.
• The parameter arg is an optional parameter name
• The catch statement catches an exception whose type matches
with the type of the catch argument.
• If the parameter in the catch statement is named, then the
parameter can be used in the exception handling code.
• If a catch statement does not match the exception it is skipped.
• More than one catch statement can be associated with a try
block.
• The exception handler can be identified by the keyword catch.
• catch always takes only one parameter.
Contd.
• The first handler that yields a match is
executed.
• If several catch statement matches the type of
an exception the first handler that matches
the exception type is executed.
• This way we can chain multiple exception
handlers and only the one with the correct
parameter type gets executed.
Contd.
try
{
throw exception;
}
catch(type1 arg)
{
// catch block 1
}
catch(type2 arg)
{
// catch block 2
}
……
catch(typeN arg)
{
// catch block N
}
Catch all exceptions
try
{
try {
// code here
}
catch (int n) {
throw;
}
}
catch (...) {
cout << "Exception occurred";
}
RETHROWING AN EXCEPTION
• A handler may decide to rethrow the
exception caught without processing it.
• In such a case we have to invoke throw
without any arguments as shown below
throw;
• This causes the current exception to be
thrown to the next enclosing try/catch
sequence and is caught by a catch statement
listed after the enclosing try block
Example
void myFunction()
{
try
{
throw "hello"; // throw a char *
}
catch(const char *)
{ // catch a char *
cout << "Caught char * inside myFunctionn";
throw ; // rethrow char * out of function
} // myFunction }
}
int main()
{ cout << "Startn";
try
{
myFunction();
}
catch(const char *)
{
cout << "Caught char * inside mainn";
}
cout << "End";
return 0;
}
SPECIFYING EXCEPTION
• It is possible to restrict a function to throw certain specific
exceptions by adding a throw list clause to the function definition.
• The type-list specifies the type of exception that may be thrown.
• Throwing any other kind of exception will cause abnormal
program termination.
• If you want to prevent a function from throwing any exception,
you may do so by making the type-list empty.
type function( type function(arg-list) throw(type list)
{ …
…
…
}
Contd.
• void f1(int) throw(int ,char, float)
• void f2(int) throw(int )
• A variation on the previous example is:
• void f3(int) throw(); // empty parentheses
• This declaration guarantees that no exception is
generated by the function f3.
• If a function exits through any exception that is not
allowed by an exception specification, it results in a call
to the predefined function unexpected().
• By default, unexpected() calls terminate() which by
default exits the program.
Copyright © 2003 Pearson
Education, Inc.
Slide 19
Type Conversion
• No automatic type conversions are done with
exceptions
– if double is in the exception specification, an int
cannot be thrown unless int is also in the
exception specification

More Related Content

Similar to Exceptions in C++ Object Oriented Programming.pptx

Similar to Exceptions in C++ Object Oriented Programming.pptx (20)

exception handling
exception handlingexception handling
exception handling
 
F6dc1 session6 c++
F6dc1 session6 c++F6dc1 session6 c++
F6dc1 session6 c++
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handling
 
Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingJava-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handling
 
Exception handling c++
Exception handling c++Exception handling c++
Exception handling c++
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exceptionn
ExceptionnExceptionn
Exceptionn
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
 
Exceptions in c++
Exceptions in c++Exceptions in c++
Exceptions in c++
 
java.pptx
java.pptxjava.pptx
java.pptx
 

Recently uploaded

From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 

Recently uploaded (20)

From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 

Exceptions in C++ Object Oriented Programming.pptx

  • 2. Exception Handling • General mechanism for handling abnormal conditions • Predefined exceptions: Constraint violations, I/O errors, other illegalities • User-defined exceptions • Exception handlers specify remedial actions or proper shutdown. • Exception handling (EH) allows a programmer to provide code in the program to handle run-time errors or exceptional situations – this improves reliability
  • 3. EXCEPTIONS Exceptions are run time anomalies or unusual conditions that a program may encounter during execution. Conditions such as • 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++.
  • 4. EXCEPTION HANDLING • Exceptions are of 2 kinds – Synchronous Exception: • Out of rage • Over flow • Asynchronous Exception: – Error that are caused by causes beyond the control of the program • Keyboard interrupts • In C++ only synchronous exception can be handled.
  • 5. Exception handling mechanism • Find the problem (Hit the exception) • Inform that an error has occurred (Throw the exception) • Receive the error information (Catch the exception) • Take corrective action (handle the exception) • It is basically build upon three keywords – Try – Throw – Catch
  • 6. Example #include <iostream> using namespace std; int main () { try { throw 10; } catch (int e) { cout << “We have a problem!!” << endl; } return 0; } Output : We have a problem!!!
  • 7. Contd. • The keyword try is used to preface a block of statements which may generate exceptions. • When an exception is detected, it is thrown using a throw statement in the try block. • A catch block 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.
  • 8. Contd. • Exceptions are objects used to transmit information about a problem. • If the type of the object thrown matches the arg type in the catch statement, the catch block is executed. • If they do not match, the program is aborted • Often, Exceptions are thrown by functions that are invoked from within the try blocks. • The point at which the throw is executed is called the throw point. • Once an exception is thrown to the catch block, control cannot return to the throw point.
  • 9. THROWING MECHANISM • The throw statement can have one of the following 3 forms – throw(exception) – throw exception – throw //used to re-throw a exception • The operand object exception can be of any type, including constant. • It is also possible to throw an object not intended for error handling. • Throw point can be in a deeply nested scope within a try block or in a deeply nested function call. • In any case, control is transferred to the catch statement
  • 10. THROWING MECHANISM • The throw expression accepts one parameter as its argument and this is passed to the exception handler. • You can have a number of throw statements at different parts of your try block with different values being thrown try { // code if ( x ) throw 10; // code if (y) throw 20; //code }
  • 11. CATCHING MECHANISM • The type indicates the type of exception the catch block handles. • The parameter arg is an optional parameter name • The catch statement catches an exception whose type matches with the type of the catch argument. • If the parameter in the catch statement is named, then the parameter can be used in the exception handling code. • If a catch statement does not match the exception it is skipped. • More than one catch statement can be associated with a try block. • The exception handler can be identified by the keyword catch. • catch always takes only one parameter.
  • 12. Contd. • The first handler that yields a match is executed. • If several catch statement matches the type of an exception the first handler that matches the exception type is executed. • This way we can chain multiple exception handlers and only the one with the correct parameter type gets executed.
  • 13. Contd. try { throw exception; } catch(type1 arg) { // catch block 1 } catch(type2 arg) { // catch block 2 } …… catch(typeN arg) { // catch block N }
  • 14. Catch all exceptions try { try { // code here } catch (int n) { throw; } } catch (...) { cout << "Exception occurred"; }
  • 15. RETHROWING AN EXCEPTION • A handler may decide to rethrow the exception caught without processing it. • In such a case we have to invoke throw without any arguments as shown below throw; • This causes the current exception to be thrown to the next enclosing try/catch sequence and is caught by a catch statement listed after the enclosing try block
  • 16. Example void myFunction() { try { throw "hello"; // throw a char * } catch(const char *) { // catch a char * cout << "Caught char * inside myFunctionn"; throw ; // rethrow char * out of function } // myFunction } } int main() { cout << "Startn"; try { myFunction(); } catch(const char *) { cout << "Caught char * inside mainn"; } cout << "End"; return 0; }
  • 17. SPECIFYING EXCEPTION • It is possible to restrict a function to throw certain specific exceptions by adding a throw list clause to the function definition. • The type-list specifies the type of exception that may be thrown. • Throwing any other kind of exception will cause abnormal program termination. • If you want to prevent a function from throwing any exception, you may do so by making the type-list empty. type function( type function(arg-list) throw(type list) { … … … }
  • 18. Contd. • void f1(int) throw(int ,char, float) • void f2(int) throw(int ) • A variation on the previous example is: • void f3(int) throw(); // empty parentheses • This declaration guarantees that no exception is generated by the function f3. • If a function exits through any exception that is not allowed by an exception specification, it results in a call to the predefined function unexpected(). • By default, unexpected() calls terminate() which by default exits the program.
  • 19. Copyright © 2003 Pearson Education, Inc. Slide 19 Type Conversion • No automatic type conversions are done with exceptions – if double is in the exception specification, an int cannot be thrown unless int is also in the exception specification