Catching all errors

user3103398

In my program I want to catch every error in a function. I've tried using a try/catch but the program still exits. I've set up an example of what I want to catch

#include <iostream>
#include <stack>

using namespace std;

int main()
{
    stack<string> test;
    test.push("lel");
    try {
        test.pop();
        test.pop();
    }
    catch (...) {
        cout << "Caught" << endl;
    }
    return 0;
}

This still causes the program to exit. How can I catch any error, or if it's not possible, this specific error?

Rakib

stack::pop() does not throw any exception when the stack is empty. Rather it is undefined behavior to pop from an empty stack. Since no exception is thrown, your catch clause can not catch anything, rather program terminates ( anything can happen in UB).

So about your intention of catching all error, I think it is good practice to put a try-catch in mainto catch anything that escaped from any other place, and you should be able to catch if exception is actually being thrown. Just take care of some issues:

  1. Control may not reach in your catch block in case of any UB.
  2. C++ can not handle more than one exceptions simultaneously, in that case program will most likely terminate in place where it happens (specially be careful so that exception does not leave any destructor).
  3. Throwing exception that is not in exception specification list of a function (most likely program will terminate).

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

Catching AggregateException

来自分类Dev

ReactiveCocoa catch all the errors - async network operation on collection object

来自分类常见问题

How to tell Maven to disregard SSL errors (and trusting all certs)?

来自分类Dev

Catching exceptions in destructors

来自分类Dev

Catching TimeoutExpired exception in Python 3.3

来自分类Dev

Catching exception from worker thread in the main thread

来自分类Dev

Catching PHP Parser error when using include

来自分类Dev

Bower Installation Errors

来自分类Dev

How to hide cat errors?

来自分类Dev

Swift Sprite Kit Errors

来自分类Dev

Handling errors with iostream

来自分类Dev

Using HttpResponseMessage to view errors

来自分类Dev

Expressjs - Handling Errors With Middleware

来自分类Dev

Android Gradle Build Errors

来自分类Dev

carrierwave Excon :: Errors :: SocketError

来自分类Dev

Hard-drive errors

来自分类Dev

PHP display_errors

来自分类Dev

SSD SMART errors and strange dmesg errors, is this a dying disk?

来自分类Dev

ServiceStack Razor Views Compilation errors

来自分类Dev

无效的盐(BCrypt :: Errors :: InvalidSalt)

来自分类Dev

ActiveModel :: Errors中的编码问题

来自分类Dev

Hide errors and warnings from console

来自分类Dev

Serializing the errors hash in ActiveModel::Serializer

来自分类Dev

mongoengine.errors.InvalidQueryError的原因

来自分类Dev

Haskell cabal-install errors

来自分类Dev

ReactJS Handling Form Errors With MaterialUI

来自分类Dev

Laravel 4中$ errors的结构

来自分类Dev

mongoengine.errors.InvalidQueryError的原因

来自分类Dev

discord.errors.HTTPException 问题