Exception Handling (Standard)
Exception Handling (Standard)
Unit 1
C++ Exceptions
try {
// Block of code to try
throw exception;
// Throw an exception when a problem arise
}
catch ()
{
// Block of code to handle errors
}
Example
try {
int age = 15;
if (age >= 18)
{
cout << "Access granted - you are old enough.";
}
else {
throw (age);
}
}
catch (int myNum)
{
cout << "Access denied - You must be at least 18 years old.\n";
cout << "Age is: " << myNum;
}
Example explained
#include <iostream>
using namespace std;
int main()
{
int x = -1;
try {
cout << "Inside try \n";
if (x < 0)
{
throw x;
cout << "After throw \n";
}
}
catch (int x ) {
cout << "Exception Caught \n";
}
cout << "After catch \n";
return 0;
}
• When an exception is thrown, lines of try block after the throw
statement are not executed.
#include<iostream>
using namespace std;
int main()
{
try
{
throw 'a';
}
catch (int param)
{
cout << "int exception\n";
}
catch (...)
{
cout << "default exception\n";
}
cout << "After Exception";
return 0;
Output
• default exception
• After Exception