How to Throw Out of Range Exception in C++?

Throw Out of range exception in C++?

Are you new to exception handling and are worried about how to throw the “out of range” exceptions in your C++ (CPP) program? Then, this article is just for you!

In computer programming, exception handling is one the most powerful techniques to handle errors before crashing the program with the help of the throw keyword

In this article, we’ll discuss what is exception handling, and how to use try-catch blocks to handle errors before they crash your C++ program. Furthermore, talk about the out of range exception and how to throw it. So let’s get right into the topic 👇. Before moving on, let’s briefly discuss exceptions and exception handling in C++.

 

 

What is Exception Handling in C++?

An exception is a runtime error that disturbs a program’s normal flow of instructions. It is an unwanted event that is not expected to occur in the normal execution of the program.

Catching exceptions and responding to unwanted events is a method of handling these errors and it is known as exception handling. We can handle exceptions using the try-catch blocks in C++ and throw exceptions using the throw keyword.

 

 

How to Handle Exceptions Using Try-Catch Block in C++?

The basis of Exception handling is the try-catch block. A try-catch block is placed around the code where there is a chance of exception occurrence.

Using the try keyword, a program throws an exception whenever a problem is caught in the program by the C++ compiler. The catch keyword catches the exceptions, and the try keyword shows the part of the code where that specific error occurs.

Let’s see an example for more clarification.

 

Code

#include <iostream>


using namespace std;

double divide(int a, int b)
{

   if( b == 0 ) {

      throw "Division by 0 is Undefined Operation";

   }

  return (a/b);

}

int main ()
{

  int c,d;

  cout<<"Enter 2 Values for Divison"<<endl;

   cin>>c>>d;

  double z = 0;


   try 

  {
z = divide(c,d);

     cout << z;

      cout<<endl;} 


   catch (const char* msg)  {

    cerr << msg << endl; }

   return 0;

}

 

Output

 

This example will throw an undefined condition error after being caught in the catch block, as shown in the output below.

After getting the invalid condition, the exception is thrown, and the char message is displayed after the exception is caught. As in this example, we are raising an exception of const char* type, so for catching this exception, we used const char* in the catch block.

 

 

Why Do We Throw Exceptions in C++?

We can create a custom exception with the help of the throw keyword. Exceptions in C++  identify the error conditions and handle them. An exception gives us a clean separation between the codes that identify some errors and the codes that throw and handle the errors. 

Using exception handling in yourC++ is a good practice to check for error conditions that can occur at runtime, no matter if your code is 100% correct.

 

 

What is an Out of Range Exception in C++?

The “Out of range”  is a standard exception that programs can throw. Some segments of the standard library, like vector, deque, string, and bitset, also throw exceptions out of range.

Let’s see an example of an “out of range” exception.

 

Code

// The out_of_range example in C++

#include <iostream>

#include <string>


using namespace std;


int main()
{

try

{
string mystr1("Zeshan");

// mystr2 index from 0 to 10

string mystr2("Programmer");


// name.append(string, start index, no of character)

//pass number of character from starting index to no of character

// generate runtime error if starting index more then 10

mystr1.append(mystr2, 11, 2);


cout<<mystr1<<endl;

}


catch (exception &e)

{

cerr<<"Caught exception: "<<e.what()<<endl;

cerr<<"Type of exception: "<<typeid(e).name()<<endl;

};

return 0;

}

 

Output

 

 

How to Throw Out of range Exception in C++?

To throw an “out of range” exception, you can use the out_of_range() constructor, which is defined in the C++ library. You can throw the exception using the throw statement.

The “out of range” exception is thrown when the arguments passed to the method contain any value that is not included in the expected values. It helps in understanding the cause of exceptions.

Let’s take this simple example of throwing an exception in a C++ program:

 

Code

#include <iostream>

using namespace std;


int main()
{

   int a;

    cout<<"Enter value less then 50:";

   cin>>a; 


//check the value of a

    if (a<50)

   {

       cout<<"You enter valid value";

    }

    else

   {

    //throw when an exception occurs

        throw std::out_of_range("You enter invalid value");

   }

   return 0;
}

 

Output

 

This program will throw an out-of-range exception when the user enters a value greater than 50.

The operand of the throw keyword tells the exception type, and the type of the result of the expression tells the type of exception thrown. Std::out_of_range reports errors that attempt to access the elements out of the defined range in the program.

 

 

Conclusion

In conclusion, throwing “out of range” exceptions in C++ is a simple and efficient way to check whether data is in the given range. We can throw a custom exception to fulfill our criteria.

Let’s have a quick recap of the topics discussed in this article.

  1. What are exceptions and exception handling?
  2. What are try-catch blocks? 
  3. Why do we throw exceptions?
  4. How can we throw std::out_of_range in our program?

Hopefully, you’ve found the above article helpful in throwing out of range exceptions in C++. If you have any questions, feel free to let us know in the comments section below 👇.

Happy coding!

 

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts
Total
0
Share