Exceptions in C++ are used to handle errors and exceptional situations gracefully without crashing the program. They provide a way to transfer control from one part of a program to another.
A try-catch block is used to handle exceptions. The code that may throw an exception is placed inside the try block, and the catch block handles the exception.
#include <iostream>
using namespace std;
int main() {
try {
throw 20;
} catch (int e) {
cout << "An exception occurred. Exception Nr. " << e << endl;
}
return 0;
}
Console Output:
An exception occurred. Exception Nr. 20
You can have multiple catch blocks to handle different types of exceptions separately.
#include <iostream>
using namespace std;
int main() {
try {
throw 'a';
} catch (int e) {
cout << "Integer exception caught." << endl;
} catch (char e) {
cout << "Character exception caught." << endl;
}
return 0;
}
Console Output:
Character exception caught.
The catch(...) block is used to catch all types of exceptions. It must be the last catch block.
#include <iostream>
using namespace std;
int main() {
try {
throw 5.5;
} catch (...) {
cout << "Default exception caught." << endl;
}
return 0;
}
Console Output:
Default exception caught.
You can throw an exception explicitly using the throw keyword followed by an exception object or value.
#include <iostream>
using namespace std;
void checkNumber(int num) {
if (num < 0) {
throw "Negative number not allowed.";
}
}
int main() {
try {
checkNumber(-1);
} catch (const char* msg) {
cout << "Exception: " << msg << endl;
}
return 0;
}
Console Output:
Exception: Negative number not allowed.
You can define your own exception classes by extending the standard exception class.
#include <iostream>
#include <exception>
using namespace std;
class MyException : public exception {
public:
const char* what() const throw() {
return "My custom exception";
}
};
int main() {
try {
throw MyException();
} catch (MyException& e) {
cout << e.what() << endl;
}
return 0;
}
Console Output:
My custom exception
You can rethrow an exception from a catch block to be handled further up the call stack.
#include <iostream>
using namespace std;
void function1() {
try {
throw 100;
} catch (int e) {
cout << "Caught in function1, rethrowing..." << endl;
throw;
}
}
int main() {
try {
function1();
} catch (int e) {
cout << "Caught in main: " << e << endl;
}
return 0;
}
Console Output:
Caught in function1, rethrowing...
Caught in main: 100
In C++, you can specify the exceptions a function might throw using the noexcept keyword.
#include <iostream>
using namespace std;
void mayThrow() noexcept(false) {
throw 42;
}
int main() {
try {
mayThrow();
} catch (int e) {
cout << "Caught exception: " << e << endl;
}
return 0;
}
Console Output:
Caught exception: 42
When an exception is thrown, C++ performs stack unwinding, which involves the destruction of all objects in the scope of the try block.
#include <iostream>
using namespace std;
class Test {
public:
~Test() {
cout << "Destructor called" << endl;
}
};
int main() {
try {
Test t;
throw 1;
} catch (int e) {
cout << "Exception caught" << endl;
}
return 0;
}
Console Output:
Destructor called
Exception caught
C++ provides a set of standard exceptions defined in the <exception> header, such as std::out_of_range, std::invalid_argument, etc.
#include <iostream>
#include <stdexcept>
using namespace std;
int main() {
try {
throw out_of_range("Out of range error");
} catch (out_of_range& e) {
cout << "Caught: " << e.what() << endl;
}
return 0;
}
Console Output:
Caught: Out of range error
Newsletter
Subscribe to our newsletter for weekly updates and promotions.
Wiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterCompany
About usCareersPressCompany
About usCareersPressCompany
About usCareersPressLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesCompany
About usCareersPressCompany
About usCareersPressCompany
About usCareersPressLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesAds Policies