SlideShare ist ein Scribd-Unternehmen logo
1 von 13
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.

Weitere ähnliche Inhalte

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

Object Oriented Programming Using C++: C++ Exception Handling.pptx
Object Oriented Programming Using C++: C++ Exception Handling.pptxObject Oriented Programming Using C++: C++ Exception Handling.pptx
Object Oriented Programming Using C++: C++ Exception Handling.pptxRashidFaridChishti
 
Exception handling
Exception handlingException handling
Exception handlingWaqas Abbasi
 
Exception Handling
Exception HandlingException Handling
Exception HandlingReddhi Basu
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handlingraksharao
 
Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingJava-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingraksharao
 
6-Exception Handling and Templates.pptx
6-Exception Handling and Templates.pptx6-Exception Handling and Templates.pptx
6-Exception Handling and Templates.pptxSatyamMishra237306
 
Unit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentUnit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentrohitgudasi18
 
Pi j4.2 software-reliability
Pi j4.2 software-reliabilityPi j4.2 software-reliability
Pi j4.2 software-reliabilitymcollison
 
Exceptions in C++ Object Oriented Programming.pptx
Exceptions in C++ Object Oriented Programming.pptxExceptions in C++ Object Oriented Programming.pptx
Exceptions in C++ Object Oriented Programming.pptxestorebackupr
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overviewBharath K
 
Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allCh-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allHayomeTakele
 
Java class 7
Java class 7Java class 7
Java class 7Edureka!
 
CAP444Unit6ExceptionHandling.pptx
CAP444Unit6ExceptionHandling.pptxCAP444Unit6ExceptionHandling.pptx
CAP444Unit6ExceptionHandling.pptxSatyajeetGaur2
 

Ähnlich wie Lecture 09 Exception Handling(1 ) in c++.pptx (20)

Unit iii
Unit iiiUnit iii
Unit iii
 
Exception_Handling.pptx
Exception_Handling.pptxException_Handling.pptx
Exception_Handling.pptx
 
Object Oriented Programming Using C++: C++ Exception Handling.pptx
Object Oriented Programming Using C++: C++ Exception Handling.pptxObject Oriented Programming Using C++: C++ Exception Handling.pptx
Object Oriented Programming Using C++: C++ Exception Handling.pptx
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling in java
Exception handling in java Exception handling in java
Exception handling in java
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
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
 
Handling
HandlingHandling
Handling
 
6-Exception Handling and Templates.pptx
6-Exception Handling and Templates.pptx6-Exception Handling and Templates.pptx
6-Exception Handling and Templates.pptx
 
Unit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentUnit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application development
 
Pi j4.2 software-reliability
Pi j4.2 software-reliabilityPi j4.2 software-reliability
Pi j4.2 software-reliability
 
Exceptions in C++ Object Oriented Programming.pptx
Exceptions in C++ Object Oriented Programming.pptxExceptions in C++ Object Oriented Programming.pptx
Exceptions in C++ Object Oriented Programming.pptx
 
Exceptionn
ExceptionnExceptionn
Exceptionn
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allCh-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for all
 
Java class 7
Java class 7Java class 7
Java class 7
 
Java Day-5
Java Day-5Java Day-5
Java Day-5
 
CAP444Unit6ExceptionHandling.pptx
CAP444Unit6ExceptionHandling.pptxCAP444Unit6ExceptionHandling.pptx
CAP444Unit6ExceptionHandling.pptx
 

Mehr von ZenLooper

File_handling in c++ and its use cases.pptx
File_handling in c++ and its use cases.pptxFile_handling in c++ and its use cases.pptx
File_handling in c++ and its use cases.pptxZenLooper
 
set identities and their examples outlined.pptx
set identities and their examples outlined.pptxset identities and their examples outlined.pptx
set identities and their examples outlined.pptxZenLooper
 
mathematical induction and stuff Induction.pptx
mathematical induction and stuff Induction.pptxmathematical induction and stuff Induction.pptx
mathematical induction and stuff Induction.pptxZenLooper
 
sets and their introduction and their exercises.pptx
sets and their introduction and their exercises.pptxsets and their introduction and their exercises.pptx
sets and their introduction and their exercises.pptxZenLooper
 
Managing External Environment and Organizational Culture.pdf
Managing External Environment and Organizational Culture.pdfManaging External Environment and Organizational Culture.pdf
Managing External Environment and Organizational Culture.pdfZenLooper
 
Planning Work Activities and their benefits.pdf
Planning Work Activities and their benefits.pdfPlanning Work Activities and their benefits.pdf
Planning Work Activities and their benefits.pdfZenLooper
 
Managers as Decision Makersstoiiiiii.pdf
Managers as Decision Makersstoiiiiii.pdfManagers as Decision Makersstoiiiiii.pdf
Managers as Decision Makersstoiiiiii.pdfZenLooper
 
rules of inference in discrete structures
rules of inference in discrete structuresrules of inference in discrete structures
rules of inference in discrete structuresZenLooper
 
Arguments in discreate structures and stuff
Arguments in discreate structures and stuffArguments in discreate structures and stuff
Arguments in discreate structures and stuffZenLooper
 
Laws of Logic in Discrete Structures and their applications
Laws of Logic in Discrete Structures and their applicationsLaws of Logic in Discrete Structures and their applications
Laws of Logic in Discrete Structures and their applicationsZenLooper
 
Discreate Truth tables and laws of logic
Discreate Truth tables and laws of logicDiscreate Truth tables and laws of logic
Discreate Truth tables and laws of logicZenLooper
 
discrete structures and their introduction
discrete structures and their introductiondiscrete structures and their introduction
discrete structures and their introductionZenLooper
 

Mehr von ZenLooper (12)

File_handling in c++ and its use cases.pptx
File_handling in c++ and its use cases.pptxFile_handling in c++ and its use cases.pptx
File_handling in c++ and its use cases.pptx
 
set identities and their examples outlined.pptx
set identities and their examples outlined.pptxset identities and their examples outlined.pptx
set identities and their examples outlined.pptx
 
mathematical induction and stuff Induction.pptx
mathematical induction and stuff Induction.pptxmathematical induction and stuff Induction.pptx
mathematical induction and stuff Induction.pptx
 
sets and their introduction and their exercises.pptx
sets and their introduction and their exercises.pptxsets and their introduction and their exercises.pptx
sets and their introduction and their exercises.pptx
 
Managing External Environment and Organizational Culture.pdf
Managing External Environment and Organizational Culture.pdfManaging External Environment and Organizational Culture.pdf
Managing External Environment and Organizational Culture.pdf
 
Planning Work Activities and their benefits.pdf
Planning Work Activities and their benefits.pdfPlanning Work Activities and their benefits.pdf
Planning Work Activities and their benefits.pdf
 
Managers as Decision Makersstoiiiiii.pdf
Managers as Decision Makersstoiiiiii.pdfManagers as Decision Makersstoiiiiii.pdf
Managers as Decision Makersstoiiiiii.pdf
 
rules of inference in discrete structures
rules of inference in discrete structuresrules of inference in discrete structures
rules of inference in discrete structures
 
Arguments in discreate structures and stuff
Arguments in discreate structures and stuffArguments in discreate structures and stuff
Arguments in discreate structures and stuff
 
Laws of Logic in Discrete Structures and their applications
Laws of Logic in Discrete Structures and their applicationsLaws of Logic in Discrete Structures and their applications
Laws of Logic in Discrete Structures and their applications
 
Discreate Truth tables and laws of logic
Discreate Truth tables and laws of logicDiscreate Truth tables and laws of logic
Discreate Truth tables and laws of logic
 
discrete structures and their introduction
discrete structures and their introductiondiscrete structures and their introduction
discrete structures and their introduction
 

Kürzlich hochgeladen

Sternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading RoomSternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading RoomSean M. Fox
 
An Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge AppAn Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge AppCeline George
 
SURVEY I created for uni project research
SURVEY I created for uni project researchSURVEY I created for uni project research
SURVEY I created for uni project researchCaitlinCummins3
 
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...Nguyen Thanh Tu Collection
 
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptxAnalyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptxLimon Prince
 
Spring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community PartnershipsSpring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community Partnershipsexpandedwebsite
 
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...Nguyen Thanh Tu Collection
 
How To Create Editable Tree View in Odoo 17
How To Create Editable Tree View in Odoo 17How To Create Editable Tree View in Odoo 17
How To Create Editable Tree View in Odoo 17Celine George
 
8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital Management8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital ManagementMBA Assignment Experts
 
An overview of the various scriptures in Hinduism
An overview of the various scriptures in HinduismAn overview of the various scriptures in Hinduism
An overview of the various scriptures in HinduismDabee Kamal
 
e-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi Rajagopale-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi RajagopalEADTU
 
SPLICE Working Group: Reusable Code Examples
SPLICE Working Group:Reusable Code ExamplesSPLICE Working Group:Reusable Code Examples
SPLICE Working Group: Reusable Code ExamplesPeter Brusilovsky
 
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjjStl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjjMohammed Sikander
 
Championnat de France de Tennis de table/
Championnat de France de Tennis de table/Championnat de France de Tennis de table/
Championnat de France de Tennis de table/siemaillard
 
Major project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategiesMajor project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategiesAmanpreetKaur157993
 
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUMDEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUMELOISARIVERA8
 
Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...EduSkills OECD
 
Dementia (Alzheimer & vasular dementia).
Dementia (Alzheimer & vasular dementia).Dementia (Alzheimer & vasular dementia).
Dementia (Alzheimer & vasular dementia).Mohamed Rizk Khodair
 

Kürzlich hochgeladen (20)

Sternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading RoomSternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
 
An Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge AppAn Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge App
 
Mattingly "AI and Prompt Design: LLMs with NER"
Mattingly "AI and Prompt Design: LLMs with NER"Mattingly "AI and Prompt Design: LLMs with NER"
Mattingly "AI and Prompt Design: LLMs with NER"
 
SURVEY I created for uni project research
SURVEY I created for uni project researchSURVEY I created for uni project research
SURVEY I created for uni project research
 
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
 
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptxAnalyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
 
Spring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community PartnershipsSpring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community Partnerships
 
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
 
How To Create Editable Tree View in Odoo 17
How To Create Editable Tree View in Odoo 17How To Create Editable Tree View in Odoo 17
How To Create Editable Tree View in Odoo 17
 
8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital Management8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital Management
 
Including Mental Health Support in Project Delivery, 14 May.pdf
Including Mental Health Support in Project Delivery, 14 May.pdfIncluding Mental Health Support in Project Delivery, 14 May.pdf
Including Mental Health Support in Project Delivery, 14 May.pdf
 
An overview of the various scriptures in Hinduism
An overview of the various scriptures in HinduismAn overview of the various scriptures in Hinduism
An overview of the various scriptures in Hinduism
 
e-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi Rajagopale-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi Rajagopal
 
SPLICE Working Group: Reusable Code Examples
SPLICE Working Group:Reusable Code ExamplesSPLICE Working Group:Reusable Code Examples
SPLICE Working Group: Reusable Code Examples
 
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjjStl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
 
Championnat de France de Tennis de table/
Championnat de France de Tennis de table/Championnat de France de Tennis de table/
Championnat de France de Tennis de table/
 
Major project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategiesMajor project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategies
 
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUMDEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
 
Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...
 
Dementia (Alzheimer & vasular dementia).
Dementia (Alzheimer & vasular dementia).Dementia (Alzheimer & vasular dementia).
Dementia (Alzheimer & vasular dementia).
 

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.