SlideShare a Scribd company logo
Object Oriented
Programming
Exception Handling
Exception Handling
• Exceptions are errors that occur at runtime.
• They are caused by a wide variety of exceptional circumstance, such
as running out of memory, not being able to open a file, trying to
initialize an object to an impossible value.
• The process of handling these exceptions is called exception handling.
• Using the exception handling mechanism, the control from one part
of the program where the exception occurred can be transferred to
another part of the code.
• Using exception handling in C++, we can handle the exceptions so
that our program keeps running.
Exception Handling
• C++ provides an inbuilt feature for Exception Handling.
• It can be done using the following specialized keywords: try, catch,
and throw with each having a different purpose.
try {
// Code that might throw an exception
throw SomeExceptionType("Error message");
}
catch( ExceptionName e1 ) {
// catch block catches the exception that is thrown from try block
}
#include <iostream>
#include <stdexcept>
using namespace std;
int main()
{
// try block
try {
int numerator = 10;
int denominator = 0;
int res;
// check if denominator is 0 then throw runtime
// error.
if (denominator == 0) {
throw runtime_error(
"Division by zero not allowed!");
}
// calculate result if no exception occurs
res = numerator / denominator;
//[printing result after division
cout << "Result after division: " << res << endl;
}
// catch block to catch the thrown exception
catch (const exception& e) {
// print the exception
cout << "Exception " << e.what() << endl;
}
return 0;
}
Output
Exception Division by zero not allowed!
#include <iostream>
using namespace std;
int main()
{
int x = -1;
// Some code
cout << "Before try n";
// try block
try {
cout << "Inside try n";
if (x < 0) {
// throwing an exception
throw x;
cout << "After throw (Never executed) n";
}
}
// catch block
catch (int x) {
cout << "Exception Caught n";
}
cout << "After catch (Will be executed) n";
return 0;
}
Output
Before try Inside try Exception Caught After catch
(Will be executed)
Special Catch block
• There is a special catch block called the ‘catch-all’ block, written as catch(…), that
can be used to catch all types of exceptions.
#include <iostream>
using namespace std;
int main()
{
// try block
try {
// throw
throw 10;
}
// catch block
catch (char* excp) {
cout << "Caught " << excp;
}
// catch all
catch (...) {
cout << "Default Exceptionn";
}
return 0;
}
Output
Default Exception
C++ Standard Exceptions
Standard Exception classes
• Standard Exception Classes:
• C++ provides several standard exception classes, such as
std::runtime_error, std::logic_error, std::invalid_argument, etc., which
can be used to represent different types of errors.
Standard Exception classes
Practice Question
• Write a C++ function named calculateSumOfSquares that takes three parameters of type int. The function
should calculate the sum of squares of all the parameters if the following conditions are met:
• All parameters are different.
• All parameters are positive.
• All parameters are odd.
If any of these conditions are not met, the function should throw different exceptions:
• If the parameters are not different, throw an exception with the message "Parameters must be different".
• If any parameter is not positive, throw an exception with the message "Parameters must be positive".
• If any parameter is not odd, throw an exception with the message "Parameters must be odd".
In the main function:
• Prompt the user to input three integers.
• Call the calculateSumOfSquares function with the user-provided integers as arguments.
• Handle any exceptions thrown by the function and display appropriate error messages.
• If no exceptions are thrown, display the calculated sum of squares.
Exception Handling in classes
Exception Handling in classes
• Consider Book chapter#14 example for Practice.

More Related Content

PPT
Week7 exception handling
PPT
Week7 exception handling
PPT
Week7 exception handling
PDF
Exception Handling
PPTX
Object Oriented Programming Using C++: C++ Exception Handling.pptx
PPTX
Exception Handling in C++-Brief notes.pptx
PPT
Exception_Handling_in_C__1701342048430.ppt
PPTX
Exception handling c++
Week7 exception handling
Week7 exception handling
Week7 exception handling
Exception Handling
Object Oriented Programming Using C++: C++ Exception Handling.pptx
Exception Handling in C++-Brief notes.pptx
Exception_Handling_in_C__1701342048430.ppt
Exception handling c++

Similar to Lecture 09 Exception Handling(1 ) in c++.pptx (20)

PPT
Exception handling
PPT
Vc++ 4(exception handling)
PPT
F6dc1 session6 c++
PDF
Exceptions ref
 
PPT
Week7_ExceptionHandling.ppt
PPT
Exception handling and templates
PPT
Handling
PPTX
6-Exception Handling and Templates.pptx
PPTX
Lecture 1 Try Throw Catch.pptx
PPT
Unit iii
PPT
Exception and Error Handling in C++ - A detailed Presentation
PPTX
Lecture 3.1.1 Try Throw Catch.pptx
PDF
PDF
PDF
Oop10 6
PPTX
Project on c++ programming. Bsc.cs students
PPT
UNIT III.ppt
PPT
UNIT III (2).ppt
PPTX
Namespaces
PPTX
WINSEM2016-17_CSE1002_LO_1336_24-JAN-2017_RM003_session 10.pptx
Exception handling
Vc++ 4(exception handling)
F6dc1 session6 c++
Exceptions ref
 
Week7_ExceptionHandling.ppt
Exception handling and templates
Handling
6-Exception Handling and Templates.pptx
Lecture 1 Try Throw Catch.pptx
Unit iii
Exception and Error Handling in C++ - A detailed Presentation
Lecture 3.1.1 Try Throw Catch.pptx
Oop10 6
Project on c++ programming. Bsc.cs students
UNIT III.ppt
UNIT III (2).ppt
Namespaces
WINSEM2016-17_CSE1002_LO_1336_24-JAN-2017_RM003_session 10.pptx
Ad

More from ZenLooper (12)

PPTX
File_handling in c++ and its use cases.pptx
PPTX
set identities and their examples outlined.pptx
PPTX
mathematical induction and stuff Induction.pptx
PPTX
sets and their introduction and their exercises.pptx
PDF
Managing External Environment and Organizational Culture.pdf
PDF
Planning Work Activities and their benefits.pdf
PDF
Managers as Decision Makersstoiiiiii.pdf
PPTX
rules of inference in discrete structures
PPTX
Arguments in discreate structures and stuff
PPTX
Laws of Logic in Discrete Structures and their applications
PPTX
Discreate Truth tables and laws of logic
PPTX
discrete structures and their introduction
File_handling in c++ and its use cases.pptx
set identities and their examples outlined.pptx
mathematical induction and stuff Induction.pptx
sets and their introduction and their exercises.pptx
Managing External Environment and Organizational Culture.pdf
Planning Work Activities and their benefits.pdf
Managers as Decision Makersstoiiiiii.pdf
rules of inference in discrete structures
Arguments in discreate structures and stuff
Laws of Logic in Discrete Structures and their applications
Discreate Truth tables and laws of logic
discrete structures and their introduction
Ad

Recently uploaded (20)

PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
Anesthesia in Laparoscopic Surgery in India
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
01-Introduction-to-Information-Management.pdf
PDF
Classroom Observation Tools for Teachers
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
Pre independence Education in Inndia.pdf
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
Sports Quiz easy sports quiz sports quiz
PPTX
GDM (1) (1).pptx small presentation for students
PPTX
Lesson notes of climatology university.
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Abdominal Access Techniques with Prof. Dr. R K Mishra
Anesthesia in Laparoscopic Surgery in India
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
01-Introduction-to-Information-Management.pdf
Classroom Observation Tools for Teachers
Module 4: Burden of Disease Tutorial Slides S2 2025
Pre independence Education in Inndia.pdf
2.FourierTransform-ShortQuestionswithAnswers.pdf
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Sports Quiz easy sports quiz sports quiz
GDM (1) (1).pptx small presentation for students
Lesson notes of climatology university.
STATICS OF THE RIGID BODIES Hibbelers.pdf
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
Microbial diseases, their pathogenesis and prophylaxis
3rd Neelam Sanjeevareddy Memorial Lecture.pdf

Lecture 09 Exception Handling(1 ) in c++.pptx

  • 2. Exception Handling • Exceptions are errors that occur at runtime. • They are caused by a wide variety of exceptional circumstance, such as running out of memory, not being able to open a file, trying to initialize an object to an impossible value. • The process of handling these exceptions is called exception handling. • Using the exception handling mechanism, the control from one part of the program where the exception occurred can be transferred to another part of the code. • Using exception handling in C++, we can handle the exceptions so that our program keeps running.
  • 3. Exception Handling • C++ provides an inbuilt feature for Exception Handling. • It can be done using the following specialized keywords: try, catch, and throw with each having a different purpose. try { // Code that might throw an exception throw SomeExceptionType("Error message"); } catch( ExceptionName e1 ) { // catch block catches the exception that is thrown from try block }
  • 4. #include <iostream> #include <stdexcept> using namespace std; int main() { // try block try { int numerator = 10; int denominator = 0; int res; // check if denominator is 0 then throw runtime // error. if (denominator == 0) { throw runtime_error( "Division by zero not allowed!"); } // calculate result if no exception occurs res = numerator / denominator; //[printing result after division cout << "Result after division: " << res << endl; } // catch block to catch the thrown exception catch (const exception& e) { // print the exception cout << "Exception " << e.what() << endl; } return 0; } Output Exception Division by zero not allowed!
  • 5. #include <iostream> using namespace std; int main() { int x = -1; // Some code cout << "Before try n"; // try block try { cout << "Inside try n"; if (x < 0) { // throwing an exception throw x; cout << "After throw (Never executed) n"; } } // catch block catch (int x) { cout << "Exception Caught n"; } cout << "After catch (Will be executed) n"; return 0; } Output Before try Inside try Exception Caught After catch (Will be executed)
  • 6. Special Catch block • There is a special catch block called the ‘catch-all’ block, written as catch(…), that can be used to catch all types of exceptions.
  • 7. #include <iostream> using namespace std; int main() { // try block try { // throw throw 10; } // catch block catch (char* excp) { cout << "Caught " << excp; } // catch all catch (...) { cout << "Default Exceptionn"; } return 0; } Output Default Exception
  • 9. Standard Exception classes • Standard Exception Classes: • C++ provides several standard exception classes, such as std::runtime_error, std::logic_error, std::invalid_argument, etc., which can be used to represent different types of errors.
  • 11. Practice Question • Write a C++ function named calculateSumOfSquares that takes three parameters of type int. The function should calculate the sum of squares of all the parameters if the following conditions are met: • All parameters are different. • All parameters are positive. • All parameters are odd. If any of these conditions are not met, the function should throw different exceptions: • If the parameters are not different, throw an exception with the message "Parameters must be different". • If any parameter is not positive, throw an exception with the message "Parameters must be positive". • If any parameter is not odd, throw an exception with the message "Parameters must be odd". In the main function: • Prompt the user to input three integers. • Call the calculateSumOfSquares function with the user-provided integers as arguments. • Handle any exceptions thrown by the function and display appropriate error messages. • If no exceptions are thrown, display the calculated sum of squares.
  • 13. Exception Handling in classes • Consider Book chapter#14 example for Practice.