Module 5 C++
Module 5 C++
Exception Handling:
1.Exception:
When executing C++ code, different errors can occur: coding errors made by the
programmer, errors due to wrong input, or other unforeseeable things.
When an error occurs, C++ will normally stop and generate an error message. The
technical term for this is: C++ will throw an exception (throw an error).
#include <iostream>
#include <stdexcept>
int main() {
int a, b;
cout << "Enter 2 numbers: ";
cin >> a >> b;
cout << a / b;
Cout<<”End of Program”;
}
Scenario: a = 3 and b = 0
Input:
The user inputs 3 for a and 0 for b.
Execution:
The program tries to execute the division 3 / 0.
Exception:
Division by zero is undefined and will result in a runtime error. In
most systems, this will cause the program to terminate.
Key Components
try block: This block contains code that might throw an exception.
throw statement: This statement is used to signal the occurrence of an
exceptional condition. It can be used to throw an exception.
catch block: This block contains code to handle the exception. It catches and
processes the exception thrown by the throw statement.
Syntax:
try {
// Block of code to try
throw exception; // Throw an exception when a problem arise
}
catch () {
// Block of code to handle errors
}
Example:
#include <iostream>
#include <stdexcept>
int main()
{
int a, b;
cout << "Enter 2 numbers: ";
cin >> a >> b;
try
{
if (b == 0)
{
throw "Divide by zero error";
}
cout << a / b;
}
catch (const char* ch)
{
cout << "Error occurred: " << ch;
}
Scenario: a = 3 and b = 0
Input:
The user inputs 3 for a and 0 for b.
Execution:
The program enters the try block.
It checks if b is zero. Since b is zero, it throws a const char* exception
with the message "Divide by zero error".
The catch block catches this exception and prints the message "Error
occurred: Divide by zero error".
After the catch block, the program prints "End of program".
Output
Enter 2 numbers: 3 0
Error occurred: Divide by zero errorEnd of program
int main()
{
try
{
throw 5;
}
catch (int x) {
cout << "Caught " << x;
}
catch (const char* ch) {
cout << "Default Exception\n";
}
return 0;
}
Output:
Caught
Property 1
#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 Exception\n";
}
return 0;
}
Output:
Default Exception
Property 2
#include <iostream>
using namespace std;
int main()
{
try {
throw 'a';
}
catch (int x) {
cout << "Caught " << x;
}
catch (...) {
cout << "Default Exception\n";
}
return 0;
}
Output:
Default Exception
Property 3
#include <iostream>
using namespace std;
int main()
{
try {
throw 'a';
}
catch (int x) {
cout << "Caught ";
}
return 0;
}
Output
terminate called after throwing an instance of 'char'