English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The following is an example of catching a zero division error.
#include <iostream> using namespace std; int display(int x, int y) { if (y == 0) { throw "Division by zero condition!"; } return (x/y); } int main () { int a = 50; int b = 0; int c = 0; try { c = display(a, b); cout << c << endl; } catch (const char* msg) { cerr << msg << endl; } return 0; }
Output Result
Division by zero condition!
In the above program,display()
A function is defined using parameters x and y. It returns x divided by y and throws an error.
int display(int x, int y) { if (y == 0) { throw "Division by zero condition!"; } return (x/y); }
In thismain()
In the function, use the try catch block to capture errors to the catch block and print the message.
try { c = display(a, b); cout << c << endl; } catch (const char* msg) { cerr << msg << endl; }