C ++“Unhandled Exception”实现自定义异常处理程序

时间:2014-02-27 15:58:52

标签: c++ exception-handling

编辑:我想通了

嗯,我只是在花了四个多小时的挫折和困惑之后才发现了这个错误;并花时间在这里引出帮助......现在我觉得我觉得很愚蠢就足够了。

唉,问题如下:

  

我希望我的自定义异常处理程序能够捕获用户的出现   但是,没有输入字符串或搜索字符,这是完美的   合法的字符串或字符包含空格,换行符   字符或空值。因此,捕获块永远不会   即使我的validateInput方法检测到错误,也执行   值并尝试抛出异常(请注意catch块   从未执行过,因此永远不会为此创建异常对象   扔进去/允许)。

     

这相当于我的问题从未出现过任何问题   编码,我只需要移动函数调用“result =   CountCharacter :: count(stringIn,charIn);“进入try块这样   可能发生异常并且catch块运行并创建一个   “CountCharacterException”对象。

     

向所有人道歉,并且无论如何都要感谢。

说明:
我对寻求帮助有点怀疑,因为我喜欢自己解决问题,唉,我陷入困境,无法表达出能产生有意义结果的谷歌搜索。我是一名大学生,这是我一直在做的C ++家庭作业,因此,我正在寻求理解我所犯的错误,而不仅仅是解决方案,以解决问题。

背景:
分配是探索递归的用法,以搜索用户输入的字符串,用户输入的搜索字符,并输出结果。而且,我的导师希望我们将异常处理纳入作业中;并且据我所知,在运行时期间发生异常的唯一方法是未提供任何一个或两个用户输入。不需要定义和使用自定义异常处理程序。我只是为了学习而选择尝试自己创造。

附加信息:
我将我的CountCharacter类设置为静态,因为我要求创建一个对象只是为了运行字符计数功能而没有任何意义。我试图彻底评论我的代码,以便我对各种编码的推理很清楚。请记住,我是一名学生,即不要指望我的解决方案是绝对最好的和/或根据编程最佳实践所有功能都是必要的。提前感谢任何帮助我的人。

错误(即我无法解决的问题):

  

未处理的异常:System.Runtime.InteropServices.SEHException:   外部组件引发的异常。在   CountCharacter.count的_CxxThrowException(Void *, s _ThrowInfo *)(basic_string \,std :: alloc   ator> * s,SByte a)in   (省略文件目录)countcharacter.h:第14行   main()in   (省略文件目录)testcountcharacter.cpp:第62行   _mainCRTStartup()

源文件:

CounterCharacter.h

/* Filename:        CountCharacter.h
 * Last Modified:   26 February 2014
 * Author:          
 * Email:           
 * Course:          CIS354 - Algorithms and Data Structures
 * 
 * CountCharacter.h defines the static methods implemented in CountCharacter.cpp,
 * which, includes two fields for tracking found search characters (frequency) and
 * the current position of the search character (found), a recursive method count
 * that is overloaded to find said search character, and a method for validating that
 * that a user entered data (validateInput) that calls upon an exception handler
 */
#ifndef COUNTCHARACTER_H
#define COUNTCHARACTER_H
#include "CountCharacterException.h"
#include <string>

using namespace std;

class CountCharacter
{
public:
    static int count(const string& s, char a);
private:
    static int frequency; // Track number of search character occurances
    static int found; // Store current position of character search matches
    static bool valid; // Stores whether a match was found
    static bool validateInput(const string& s, char a); // Determine if required inputs are present
    static int count(const string& s, char a, int pos); // Recursive helper function
}; // end CountCharacter Class

#endif

CountCharacter.cpp

/* Filename:        CountCharacter.cpp
 * Last Modified:   26 February 2014
 * Author:          
 * Email:           
 * Course:          CIS354 - Algorithms and Data Structures
 * 
 * CountCharacter.cpp is the implementation of CountCharacter.h
 */
#include "CountCharacter.h"

    int CountCharacter::frequency = 0;
    int CountCharacter::found = 0;
    bool CountCharacter::valid = false;

int CountCharacter::count(const string& s, char a)
{
    if( !validateInput( s, a ) )
        throw CountCharacterException( s, a );
    else
        count( s, a, 0 );
    return frequency;
} // end recursive count function

int CountCharacter::count(const string& s, char a, int pos)
{
    found = s.find_first_of( a, pos );

    if(found != std::string::npos)
    {
        frequency++;
        count( s, a , found + 1);
    }
    else
    {
        return frequency;
    }
} // end count helper function

bool CountCharacter::validateInput(const string& s, char a)
{
    if( (!s.empty()) && (a != '\0') && (a != '\n'))
    {
        valid = true;
    }

    return valid;
} // end validateInput() method

TestCountCharacter.cpp

/* Filename:        TestCountCharacter.cpp
 * Last Modified:   26 February 2014
 * Author:          
 * Email:           
 * Course:          CIS354 - Algorithms and Data Structures
 * 
 * TestCountCharacter.cpp is a test-harness programm for CountCharacter.h. It prints a
 * header from SignatureBlock.h, and two brief prompts to allow a user to 
 * test implementation of the character counting functionality provided by
 * CountCharacter.h
 */
#include "CountCharacter.h"
#include "SignatureBlock.h"
#include <iostream>
#include <string>

using namespace std;

int main()
{
    string stringIn; // User-entered string
    char charIn; // User-entered search character
    int result; // Stores whether character match was found

    SignatureBlock::printHeader(); // Print Signature Block

        // Get a string and search character from user
        try
        {
            cout << "\nEnter a string: ";
            getline( cin, stringIn );

            cout << "\nEnter a character: ";
            // Using getchar() instead of "cin >> charIn", to allow for user to NOT enter a search
            // character, and thus allow exception handling to be tested
            charIn = getchar();
            // Discard any remaining characters in the input stream. NOTE: this will be relevant
            // once the exception handling is properly working, and I place the try...catch block
            // in a do...while loop to continue prompting until valid input is received
            cin.ignore(1000, '\n');
        }
        catch( CountCharacterException& inputException)
        {
            cout << inputException.what();
            cout << "A search string, and a character to search for, must be entered.\n"
                 << "You entered String: \"" << inputException.getStringIn() << "\" and Character: \"" << inputException.getCharIn() << "\".\n" << endl;
        }

    // Call static method count with user-entered string and search character
    result = CountCharacter::count( stringIn, charIn );

    // If a character match was found
    if( result > 0 )
        cout << "\nCharacter \"" << charIn << "\" was found (" << result << ") times.\n" << endl;
    // No character match was found
    else 
        cout << "\nCharacter \"" << charIn << "\" was not found.\n" << endl;

    return 0;
}

CountCharacterException.h

/* Filename:        CountCharacterException.h
 * Last Modified:   26 February 2014
 * Author:          
 * Email:           
 * Course:          CIS354 - Algorithms and Data Structures
 * 
 * CountCharacterException.h is a custom inline exception class for CountCharacter.h
 * that extends the standard invalid_argument class to make use of the what()
 * function in the exception class. It receives inputs of the user-entered
 * string and search character, as well as functions to return said fields; and throws
 * an error message as defined in the base classe's constructor (line 23)
 */
#ifndef COUNTCHARACTEREXCEPTION_H
#define COUNTCHARACTEREXCEPTION_H
#include <stdexcept>
#include <string>

using namespace std;

class CountCharacterException : public invalid_argument
{
public:
    CountCharacterException( const string& stringIn, char charIn) : invalid_argument("Invalid Input: ")
    {
        this->stringIn = stringIn;
        this->charIn = charIn;
    }
// Accessor method for user-entered search string
string getStringIn() const
{
    return stringIn;
} // end getString() method

// Accessor method for user-entered search character
char getCharIn() const
{
    return charIn;
} // end getCharIn() method
private:
    string stringIn;
    char charIn;
}; // end CountCharacterException class

#endif

0 个答案:

没有答案