본문 바로가기

Language Proficiency/C++

Inherited Code

You inherited a piece of code that performs username validation for your company's website. The existing function works reasonably well, but it throws an exception when the username is too short. Upon review, you realize that nobody ever defined the exception.

The inherited code is provided for you in the locked section of your editor. Complete the code so that, when an exception is thrown, it prints Too short: n (where  is the length of the given username).

Input Format

The first line contains an integer, , the number of test cases. 
Each of the  subsequent lines describes a test case as a single username string, .

Constraints

  • The username consists only of uppercase and lowercase letters.

Output Format

You are not responsible for directly printing anything to stdout. If your code is correct, the locked stub code in your editor will print either Valid (if the username is valid), Invalid (if the username is invalid), or Too short: n (where  is the length of the too-short username) on a new line for each test case.

Sample Input

3
Peter
Me
Arxwwz

Sample Output

Valid
Too short: 2
Invalid

Explanation

Username Me is too short because it only contains  characters, so your exception prints 
All other validation is handled by the locked code in your editor.




알고리즘과 같은 로직을 작성하는 문제가 아니라, Exception을 처리하는 클래스를 정의하는 문제이다.

사실..지금까지 해왔던 업무에서는 STL의 예외처리를 위해 try~catch를 사용하긴 했지만, 내가 사용할 예외 처리 클래스를 별도로 정의해서 사용해본 적은 없는것 같다. C++에서 현재 기본 제공되는 예외만 해도 상당히 많은 커버를 할 수 있으니까....

하지만, 별도로 내가 처리할 예외 클래스를 작성해보는 것도 좋은 것 같다. 원리를 알고 있다면 응용은 쉬워지니까....


두가지 예제를 남겨놓는다.


예제 #1

1
2
3
4
5
6
7
8
9
10
class BadLengthException : public exception {
private:
    string sErrNum;
 
public:
    BadLengthException(int n) : sErrNum(to_string(n)) {}
    virtual const char* what() const throw() {
        return sErrNum.c_str();
    }
};



예제 #2

1
2
3
4
5
6
class BadLengthException : public std::runtime_error
{
public:
    BadLengthException(int length) : std::runtime_error{std::to_string(length)}
    { }
};



'Language Proficiency > C++' 카테고리의 다른 글

Virtual Functions  (0) 2018.08.02
Exceptional Server  (0) 2018.08.02
StringStream  (0) 2018.08.02
Vector-Sort  (0) 2018.08.01
Attribute Parser  (0) 2018.08.01