logo
down
shadow

Exception Handling in underflow while doing POP in Stack


Exception Handling in underflow while doing POP in Stack

By : user2956130
Date : November 22 2020, 10:54 AM
it should still fix some issue I want to know how to apply exception handling when the top variable reaches to a value -1 (no element left to pop). Currently, I am using cout to nofity the user about the stack underflow and returning 0, which is not a good practice. What improvement overall can be made to this pop function and how to notify user and handle the exception when stack reaches a state of underflow. , You can throw an out_of_range exception:
code :
#include <stdexcept>
int Mystack::pop()
{
    if (isEmpty())
       throw std::out_of_range("Stack Underflow");
    std::cout << "The popped element is" << A[top];
    return A[top--];
}
void foo() 
{
   Mystack ms;
   //...
  try 
  {
    ms.pop();
  }
  catch (const std::out_of_range& oor) 
  {
    std::cerr << "Out of Range error: " << oor.what() << '\n';
  }
}
#include <stdexcept>
struct myStackException : public std::exception
{
   const char *what() const noexcept { return "Stack Overflow"; }
};

int Mystack::pop()
{
    if (isEmpty())
        throw myStackException();
    std::cout << "The popped element is" << A[top];
    return A[top--];
}


Share : facebook icon twitter icon
Order of exception handling stack frames on the call stack

Order of exception handling stack frames on the call stack


By : ScottyMcG
Date : March 29 2020, 07:55 AM
hop of those help? No, adding an exception handler doesn't add a new frame to the call stack. It just adds appropriate information so that when an exception is thrown, at each level of the call stack the framework can find the appropriate handler for that exception (if indeed there is an appropriate handler).
It's a little bit like garbage collection, where at any point of execution the GC can work out which local variables should still count as GC roots - essentially there's more to a method than the executable code itself :)
Can exception handling of object whose constructor throw an exception be near its stack-based creation on code?

Can exception handling of object whose constructor throw an exception be near its stack-based creation on code?


By : Yash Trivedi
Date : March 29 2020, 07:55 AM
Hope that helps Delegate the // rest of work to a helper function, and pass a Hoge& to that function:
code :
void RestOfWork(Hoge& hoge)
{
  // rest of work here
}

void g() {
  // work unrelated to Hoge object here

  try {
    Hoge hoge;
    RestOfWork(hoge);
    // rest of work here
  } catch(HogeException& ex) {
    // handle exception
  }
}
  void RestOfWork()
  {
       Hoge hoge;
      // rest of work here
  }

  void g() {
    // work unrelated to Hoge object here

    try {
      RestOfWork();
    } catch(HogeException& ex) {
      // handle exception
    }
  }
Exception Handling with Stack in C++

Exception Handling with Stack in C++


By : Michal Sacewicz
Date : March 29 2020, 07:55 AM
may help you . In the case StackEmpty is thrown, function doesn't return anything, though it is supposed to return const E&.
code :
template <typename E >
const E& ArrayStack<E> ::top() const throw(StackEmpty)
{
    try{
        if(empty()) throw StackEmpty("Top of Empty Stack");
        return S[t];
        }
    catch(StackEmpty& se)
    {
        cout << se.getMessage()<<"\n";
        // Return operator is missing ! Possibly you want this:
        throw;
   }
}
template <typename E >
const E& ArrayStack<E> ::top() const throw(StackEmpty)
{
    if(empty()) throw StackEmpty("Top of Empty Stack");
    return S[t];
}

int main()
{
    ArrayStack <int> A;

    try
    {
        cout << "######\n";
        cout << A.top() << "\n";
        cout << "######\n";
    }
    catch(StackEmpty& se)
    {
        cout << se.getMessage()<<"\n";
    }
}
Stack by pointers in C working except at stack underflow

Stack by pointers in C working except at stack underflow


By : Deepak
Date : March 29 2020, 07:55 AM
it helps some times When you create the stack you allocate space for a node -- and don't fill it with anything. So after the call to create_stack() you have a blank node on your stack already. I guess you don't want that, doing just
code :
void create_stack(stack_node **top, int *status)
{
   *top = NULL;
   *status = PUSH -1;
}
What is the difference between stack buffer overflow, stack underflow and stack overflow?

What is the difference between stack buffer overflow, stack underflow and stack overflow?


By : user2579576
Date : March 29 2020, 07:55 AM
To fix the issue you can do First, stack and buffer are different things as you may know.
The buffer overflow happens when a program (any kind) tries to write beyond the allocated memory that it has. Imagine
code :
int myArray[5];
myArray[9]=3;
void recurse()
{
int numbers[20000];
    recurse();
}
List => [1,2,3]
List.pop => [2,3] //List.pop now contains (->) [2,3]
List.pop => [3]
List.pop => []
List.pop => ??? Stack underflow!
Related Posts Related Posts :
  • C++ Error: C4430 and C2143 Error at an impossible place
  • How can I track object lifetime in C++11 lambda?
  • #include statement mapping in Biicode (biicode.conf)
  • std::equal gives "Term doesnt evaluate to a function taking 2 arguments"
  • C++ template argument as reference lvalue
  • Legal to forward declare C standard library entities but not C++ standard library entities?
  • Conversion of wchar_t* to string
  • VirtualTreeView - Embarcadero C++ Builder XE7 - 64 bits
  • I don't understand C++ pointer arithmetic
  • Invalid addition of constness? Error: Cannot use char** to initialize const char**
  • Initilize constructor of class from another class
  • what happens when a class object is used as an index for an array?
  • Read and straighten multiple images from vector string, get error: "vector subscript out of range" [c++]
  • Meaning of a few lines in C++
  • Map, pair-vector or two vectors...?
  • Redefinition error in ostream overload in template and inherited classes
  • CUDA 6.5: error MSB3191 Unable to create directory and LNK2001 Unresolved External symbol
  • Is it possible to overlap batched FFTs with CUDA's cuFFT library and cufftPlanMany?
  • How to delete function from DLL binary
  • How do I loop over a boost MPL list of non-default constructed classes?
  • Download page using IE engine + use POST
  • How to insert an element into ublas matrix with dynamic size
  • Using typedefs appropriately to avoid "typedef contamination"
  • C++ Simple Converting from Binary to Decimal
  • error deleting item from list after passing through function
  • C++: RVO, NRVO and returning local objects
  • performance map c++ find (g++ (GCC) 4.4.7 20120313 (Red Hat 4.4.7-3))
  • How to change the fundamental underlying container type for the adaptor containers?
  • Crash when SAFE_RELEASE is called on IMMDeviceEnumerator
  • Visual Studio C++, how to change the text color for "nullptr"
  • C++ , return string from function; boost::asio read / write
  • C++ and finance, trouble understanding syntax in these files
  • C++, Mongoose: How to make a POST request?
  • boost split method results in iterator error
  • Why Would Different Pointers Act As If They Shared The Same Values?
  • g++ dumped assembly output doesn't work
  • C++ Rotation matrix issue when used on a square
  • Avoiding multiple objects of same name in C++
  • Is it possible to get Lexer output from gcc or clang?
  • C++ getline pass file or cin
  • Find critical edges of an MST: possible with modified Prim's algorithm?
  • Converting wostringstream to wchar_t* Garbles Values
  • Causing segfault in program doesn't get caught by signal handler
  • Undefined symbol: _ZN7QString13toUtf8_helperERKS_ at runtime
  • proper usage of C dummy functions replacement in different environment
  • How do you save images of detected objects in OpenCV?
  • See if length between two equal numbers in deque is even
  • Random real in [0..1[ using Mersenne Twister
  • Writing the contents of a map through operator overloading
  • Defined operator works in main() but doesn't work in class
  • Can a throw or delete expression ever be dependent?
  • C++ finding the (largest) index of the largest element in an array
  • Can sizeof nested twice ever be a dependent expression?
  • Creation of objects from a string (C++)
  • OpenCV: extractor->descriptorSize() - Segfault
  • C++ generic iterator
  • Why HANDLE created by 'CreateEvent' isn't valid in another process?
  • Assistance with a Memory Allocation Error in c++, linux using g++
  • Returning by reference a member of a destroyed local variable
  • Opengl: how do I affect the lighting on a textured plane?
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org