In C++, we have the concept of exception handling, in which we deal with errors that occur at runtime. Here in this article, we have mentioned what exceptions are and what exception handling is.
What are exceptions in C++?
An exception is a technical term in programming given to the runtime error. Exceptions are the errors that generally occur at the runtime because of some issues in the program. For example, if we try to divide a number with zero, then it will cause a ZeroDivisionError.
Exception Handling
In C++, we have 3 keywords try, catch and throw , which can deal with exceptions and provide a way to handle exceptions during the runtime. Exception handling is a technique that uses these three keywords so the program can be exempted from the errors that occur at the runtime.
try
The try block is used to test that block of code that could raise problems during runtime.
catch
The catch block is used if the try block has some errors or exceptions, and it provides an alternative block of code to the try block.
throw
the throw statement is used to throw errors and exceptions, and using the throw statement, we can create our own custom errors and exceptions.
Note
The catch block executes only if the try block has a throw statement
try….catch syntax
try { // Block of code to try throw exception; // Throw exception if there is a exception arise. } catch () { // alternative code if there is an error }
Example
#include <iostream> using namespace std; int main() { float a,b,division; try { cout<<"Enter the value of a: "; cin>>a; cout<<"Enter the value of b: "; cin>>b; if (b==0) { throw b; } } catch(int num) { cout<<"b value cannot be zero please Enter the value of b again: "; cin>>b; } division = a/b; cout<<"The value of a/b is: "<<division; return 0; }
Output
Enter the value of a: 57 Enter the value of b: 0 b value cannot be zero please Enter the value of b again: 25 The value of a/b is: 2.28
Behind the code
In this example, we ask the user to enter the value of a and b. If the user enters 0 as the value of b , then the try statement if block gets executed and which also executes the throw b ; statement. If the throw statement executes, it looks for the corresponding catch() block, so here, when the throw b; statement gets executed, the corresponding catch(float num), block gets triggered and executed too.
Summary:
- Exception handling was not in the C programming language.
- The exception is a technical name given to runtime errors.
- Exception handling is a technique used to deal with the exception.
- In C++, we have the try, catch and throw keywords for exception handling.
People are also reading:
- C++ Data Encapsulation
- Constants/Literals in C++
- C++ Multithreading
- Signal Handling in C++
- C++ Templates
- Namespaces in C++
- Best C++ IDEs and Code Editors
- Top C++ Books
- C vs C++