
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
How to catch a divide by zero error in C++?
The following is an example to catch a divide by zero error.
Example
#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
Division by zero condition!
In the above program, a function display() is defined with arguments x and y. It is returning x divide by y and throwing an error.
int display(int x, int y) { if( y == 0 ) { throw "Division by zero condition!"; } return (x/y); }
In the main() function, using try catch block, the error is caught by catch block and print the message.
try { c = display(a, b); cout << c << endl; } catch (const char* msg) { cerr << msg << endl; }
- Related Articles
- How to capture divide by zero exception in Java?
- How to capture divide by zero exception in C#?
- How to catch an assertion error in Java
- Handling the Divide by Zero Exception in C++
- How to divide each column by a particular column in R?
- How to divide a range of cells by a number in Excel?
- How to divide columns of a matrix by vector elements in R?
- ERROR 1064 (42000): You have an error in your SQL syntax at zero fill column?
- How to divide rows in a data.table object by row variance in R?
- How to divide matrix rows in R by row median?
- How to divide matrix values by row variance in R?
- How to divide each value in a data frame by column total in R?
- How to divide the matrix rows by row minimum in R?
- How to divide data.table object rows by row median in R?
- How to divide the matrix rows by row maximum in R?

Advertisements