SlideShare ist ein Scribd-Unternehmen 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.

Weitere ähnliche Inhalte

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

Unit iii
Unit iiiUnit iii
Unit iii
snehaarao19
 
Exception_Handling.pptx
Exception_Handling.pptxException_Handling.pptx
Exception_Handling.pptx
AsisKumarTripathy
 
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
RashidFaridChishti
 
Exception handling
Exception handlingException handling
Exception handling
Waqas Abbasi
 
Exception handling in java
Exception handling in java Exception handling in java
Exception handling in java
yugandhar vadlamudi
 
Exception Handling
Exception HandlingException Handling
Exception Handling
Reddhi Basu
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handling
raksharao
 
Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingJava-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handling
raksharao
 
Handling
HandlingHandling
Handling
Amit Vats
 
6-Exception Handling and Templates.pptx
6-Exception Handling and Templates.pptx6-Exception Handling and Templates.pptx
6-Exception Handling and Templates.pptx
SatyamMishra237306
 
Object Oriented Design and Programming Unit-04
Object Oriented Design and Programming Unit-04Object Oriented Design and Programming Unit-04
Object Oriented Design and Programming Unit-04
sivakumarmcs
 
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
rohitgudasi18
 
Pi j4.2 software-reliability
Pi j4.2 software-reliabilityPi j4.2 software-reliability
Pi j4.2 software-reliability
mcollison
 
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
estorebackupr
 
Exceptionn
ExceptionnExceptionn
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
Bharath K
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
GaneshKumarKanthiah
 
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
HayomeTakele
 
Java class 7
Java class 7Java class 7
Java class 7
Edureka!
 
Java Day-5
Java Day-5Java Day-5
Java Day-5
People Strategists
 

Ä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
 
Object Oriented Design and Programming Unit-04
Object Oriented Design and Programming Unit-04Object Oriented Design and Programming Unit-04
Object Oriented Design and Programming Unit-04
 
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
 

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.pptx
ZenLooper
 
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
ZenLooper
 
mathematical induction and stuff Induction.pptx
mathematical induction and stuff Induction.pptxmathematical induction and stuff Induction.pptx
mathematical induction and stuff Induction.pptx
ZenLooper
 
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
ZenLooper
 
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
ZenLooper
 
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
ZenLooper
 
Managers as Decision Makersstoiiiiii.pdf
Managers as Decision Makersstoiiiiii.pdfManagers as Decision Makersstoiiiiii.pdf
Managers as Decision Makersstoiiiiii.pdf
ZenLooper
 
rules of inference in discrete structures
rules of inference in discrete structuresrules of inference in discrete structures
rules of inference in discrete structures
ZenLooper
 
Arguments in discreate structures and stuff
Arguments in discreate structures and stuffArguments in discreate structures and stuff
Arguments in discreate structures and stuff
ZenLooper
 
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
ZenLooper
 
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
ZenLooper
 
discrete structures and their introduction
discrete structures and their introductiondiscrete structures and their introduction
discrete structures and their introduction
ZenLooper
 

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

BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
Nguyen Thanh Tu Collection
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
spot a liar (Haiqa 146).pptx Technical writhing and presentation skills
spot a liar (Haiqa 146).pptx Technical writhing and presentation skillsspot a liar (Haiqa 146).pptx Technical writhing and presentation skills
spot a liar (Haiqa 146).pptx Technical writhing and presentation skills
haiqairshad
 
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
imrankhan141184
 
How to Create a More Engaging and Human Online Learning Experience
How to Create a More Engaging and Human Online Learning Experience How to Create a More Engaging and Human Online Learning Experience
How to Create a More Engaging and Human Online Learning Experience
Wahiba Chair Training & Consulting
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
National Information Standards Organization (NISO)
 
How to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 InventoryHow to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 Inventory
Celine George
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
Priyankaranawat4
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
eBook.com.bd (প্রয়োজনীয় বাংলা বই)
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
amberjdewit93
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
RAHUL
 
Chapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptxChapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptx
Denish Jangid
 
Cognitive Development Adolescence Psychology
Cognitive Development Adolescence PsychologyCognitive Development Adolescence Psychology
Cognitive Development Adolescence Psychology
paigestewart1632
 
How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
Celine George
 
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptxPrésentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
siemaillard
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
Dr. Shivangi Singh Parihar
 
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptxBeyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
EduSkills OECD
 
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptxPengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Fajar Baskoro
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
Israel Genealogy Research Association
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
Priyankaranawat4
 

Kürzlich hochgeladen (20)

BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
 
spot a liar (Haiqa 146).pptx Technical writhing and presentation skills
spot a liar (Haiqa 146).pptx Technical writhing and presentation skillsspot a liar (Haiqa 146).pptx Technical writhing and presentation skills
spot a liar (Haiqa 146).pptx Technical writhing and presentation skills
 
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
 
How to Create a More Engaging and Human Online Learning Experience
How to Create a More Engaging and Human Online Learning Experience How to Create a More Engaging and Human Online Learning Experience
How to Create a More Engaging and Human Online Learning Experience
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
 
How to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 InventoryHow to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 Inventory
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
 
Chapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptxChapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptx
 
Cognitive Development Adolescence Psychology
Cognitive Development Adolescence PsychologyCognitive Development Adolescence Psychology
Cognitive Development Adolescence Psychology
 
How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
 
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptxPrésentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
 
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptxBeyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
 
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptxPengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptx
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).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.