We are going to create a sample application that throws and catches a custom exception and analyze how the data type choice affects efficiency. Follow these steps:
- In your working directory, that is, ~/test, create a subdirectory called catch.
- Use your favorite text editor to create a file called catch.cpp in the catch subdirectory.
- Put the definition of the Error class in the catch.cpp file:
#include <iostream>
class Error {
int code;
public:
Error(int code): code(code) {
std::cout << " Error instance " << code << " was created"
<< std::endl;
}
Error(const Error& other): code(other.code) {
std::cout << " Error instance " << code << " was cloned"
<< std::endl;
}
~Error() {
std::cout << " Error instance " << code << " was destroyed"
<< std::endl;
}
};
- Next, we add helper functions to test three different ways of throwing and handling errors. We start with the function that catches exceptions by value:
void CatchByValue() {
std::cout << "Catch by value" << std::endl;
try {
throw Error(1);
}
catch (Error e) {
std::cout << " Error caught" << std::endl;
}
}
- Then, we add a function that throws a pointer and catches the exception by pointer, as follows:
void CatchByPointer() {
std::cout << "Catch by pointer" << std::endl;
try {
throw new Error(2);
}
catch (Error* e) {
std::cout << " Error caught" << std::endl;
}
}
- Next, we add a function that uses a const reference to catch exceptions:
void CatchByReference() {
std::cout << "Catch by reference" << std::endl;
try {
throw Error(3);
}
catch (const Error& e) {
std::cout << " Error caught" << std::endl;
}
}
- After all the helper functions have been defined, we add the main function to tie everything together:
int main() {
CatchByValue();
CatchByPointer();
CatchByReference();
return 0;
}
- We put the build rules for our application into a CMakeLists.txt file:
cmake_minimum_required(VERSION 3.5.1)
project(catch)
add_executable(catch catch.cpp)
set(CMAKE_SYSTEM_NAME Linux)
set(CMAKE_SYSTEM_PROCESSOR arm)
SET(CMAKE_CXX_FLAGS "--std=c++11")
set(CMAKE_CXX_COMPILER /usr/bin/arm-linux-gnueabi-g++)
- We can now build and run the application.