An exception is a problem that arises during the execution of a program. When executing C++ code, different errors can occur: coding errors made by the programmer, errors due to wrong input, or other unforeseeable things such as an attempt to divide by zero.
Exceptions provide a way to transfer control from one part of a program to another.
C++ exception handling is built upon three keywords: try
, catch
, and throw
.
Assuming a block will raise an exception, a method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception.
Code within a try/catch block is referred to as protected code, and the syntax for using try/catch as follows −
try {
// Block of code to try
throw exception; // Throw an exception when a problem arise
}
catch () {
// Block of code to handle errors
}
// You can list down multiple catch statements to catch different type of exceptions
// in case your try block raises more than one exception in different situations.
Example
try {
string password = "test_pass";
if (password == "test_password") {
cout << "Access granted";
}
else {
throw (password);
}
}
catch (string password) {
cout << "Access denied\n";
cout << "You entered " << password;
}
We use the try
block to test some code: If the password variable is not equal to “test_password”, we will throw an exception, and handle it in our catch
block.
In the catch
block, we catch the error and do something about it. The catch
statement takes a parameter: in our example we use a string variable (password) (because we are throwing an exception of string type in the try block (password)), to output the password entered.
If no error occurs, the catch
block is skipped.
Note: If you do not know the throw
type used in the try
block, you can use the “three dots” syntax (...
) inside the catch
block, which will handle any type of exception.
Try the following example in the editor below.
You are given a function named division which throw an exception if the value of divisor is 0 as shown below. Your task is to complete the main function and use try and catch blocks. In try block call and print the value return by division function, else if an exception is thrown print the exception in catch.