An exception is an event at program runtime that alters the normal flow of the code. It can also be considered an error. C++ provides a way to handle errors without having to entirely stop the code from running.
try catch block
The try keyword wraps the bit of code intended for testing for errors in a block. try is followed by catch where you define how the flow continues when an error occurs in the try block. The syntax looks something like this
try {
int numbers[3] = {10, 20, 30};
cout << numbers[10]; // this will definitely throw an exception because the numbers array only has 3 elements.
} catch (Exception e)
// Exception is the type of the error e being handled
{
cout << "Stick to the size of the array!";
}
In some cases we may want a custom error when a particular scenario occurs. The throw keyword is used here, followed by the exception type.
try
{
int age;
if (age >= 18)
{ // do something}
else {
throw age;
}
}
catch(int e)
{
cout << "You have to be over 18 to proceed";
}
If the age entered is below 18, then the program throws an exception of type int, the age, and catches it in the catch block. Notice the catch block takes an int parameter. That’s because the type of the error thrown in the try block needs to be the same type in the catch block. You can’t throw an int exception and catch and handle a string exception.
However, the type of an exception may not always be known. In that case you can use “three dots” inside the catch block. This handles all exceptions and is many times the syntax used.
catch(...)
{ \\ code to handle the error}
Summary:
try catch comes in pairs. You can’t use one without the other.
Use the throw keyword to throw a custom error.
throw is followed by the exception type.
Specify a type in the catch block. It should match the exception type in the try block preceding it.
The “three dot” syntax can be used when you don’t know the type of exception being thrown, or when you want to handle all exceptions.
Code within a try catch block is known as “protected” code.