Introduction Sometimes we would like to keep running our program without termination even if some errors and exceptions occur. This is particularly required for applications running on the cloud. Therefore, appropriate exception handlings are very important.
In this blog post, I am going to show how to use try
and catch
block to catch the exceptions.
Example The standard C++ exception classes , such as std::runtime_error
, are usually inherited from std::exception
, we can also customize our own exception class as well.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 #include <iostream> #include <stdexcept> #include <exception> #include <limits> double division (double x, double y) { if (y == 0 ) { throw std::runtime_error{"Divisor cannot be zero!" }; } return x / y; } class bad_input_error : public std::exception { public : const char * what () const throw () { return "Got bad input!" ; } }; void readValues (double & x, double & y) { std::cout << "Please input dividend: " <<std::endl; std::cin >> x; if (!std::cin) { std::cin.clear (); std::cin.ignore (std::numeric_limits<std::streamsize>::max (), '\n' ); throw bad_input_error{}; } std::cout << "Please input divisor: " <<std::endl; std::cin >> y; if (!std::cin) { std::cin.clear (); std::cin.ignore (std::numeric_limits<std::streamsize>::max (), '\n' ); throw bad_input_error{}; } } int main () { double x; double y; double z; while (true ) { try { readValues (x, y); } catch (bad_input_error& error) { std::cerr << "Runtime error: " << error.what () << std::endl; std::cerr << "Please input values again." << std::endl; continue ; } try { z = division (x, y); std::cout << "Quotient: " << std::endl; std::cout << z << std::endl; } catch (std::runtime_error& error) { std::cerr << "Runtime error: " << error.what () << std::endl; continue ; } } return 0 ; }
To compile the program, run the following command in the terminal.
1 $ g++ exception.cpp -o exception
We run the program to compute the quotients given the input values.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 $ ./exception Please input dividend: 10 Please input divisor: 2 Quotient: 5 Please input dividend: 10 Please input divisor: 0 Runtime error: Divisor cannot be zero! Please input dividend: michael Runtime error: Got bad input! Please input values again. Please input dividend: 10 Please input divisor: 2 Quotient: 5 Please input dividend:
Conclusions Exception handling is very important for programs in production.