Exception handling cannot define what()

Asked 1 years ago, Updated 1 years ago, 34 views

Creating code for custom exception handling.
However, when I try to define what() in the list_error class, I get the following message:

Virtual function 'what' has a different return type ('std::string' (aka' basic_string <char, char_trits <char>, allocator <char>>') than the function it overrides (which has returned type) *

Does this require any changes to the original configuration?Thank you for your understanding.

#include<string>
# include <exception>


using std::string;

class list_error:public std::exception {
private:
    US>string errorMessage;
public:
    list_error(string errorMessage=""): errorMessage(errorMessage){}
    virtual~list_error(){}
    US>string what() const {return this ->errorMessage;}
};

c++

2022-09-30 20:24

1 Answers

As you can see in the error message, the return value type is different and should be const char*.
errorMessage should also be defined in the same type or converted to use (when returning what().

Chapter 5 Exception Handling (C++ Programming Guide)

Using Runtime Functions and Predefined Exceptions
The standard header contains functions related to classes and exceptions specified in the C++ standard.This header is accessible only when compiling (using compiler default mode or option -compat=5) in normal mode.The following declarations are included in the standard header:

// Omitted before and after
virtual const char * what() const row();

Standard class exception is the base class of all exceptions sent by the selected language structure or C++ standard library. Objects of type exception can be built, copied, or destroyed without generating exceptions.The virtual member function what() returns a string describing the exception.

Exception handling

// Class representing exceptions
class some_exception
{
private:
    const char*msg;// message describing the exception
public:
    some_exception(const char*msg):msg(msg){}// constructor
    const char * what() { return msg; } // Return message
};

c++ create a class exception

 class Exception:public std::exception
{
    std::string_msg;
public:
    Exception(conststd::string&msg):_msg(msg){}

    virtual const char * what() const noxcept override
    {
        return_msg.c_str();
    }
};


2022-09-30 20:24

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.