C++-User defined exceptions

Delgersaikhan
2 min readNov 14, 2019

--

Hey there! Today we’re gonna talk about user defined exceptions in C++. To understand this concept you need to be learnt about class and inheritance, concept of exceptions and exception handling in C++.

Exceptions are useful when you want to catch logical errors in your code. For example you can throw exceptions when checking passwords. Let’s say that the password must consists of at least 6 characters. If we write a exception for this case, when the program receives a password in length of 5 characters it will throw an exception so that we could know the password is not valid.

Task:

Write a exception class that throws an exception when the username is too short. We are only responsible for write the class. Other things are provided in editor.

Input: Username length N

Output: Also Username length N

User defined exception classes inherit exception class provided by C++ and overrides it’s functionality according to our needs.

To use class exception we must include exception header using the pre-processor directive.

#include <exception>

The inherited classes in C++ are written with colon, access type and inheriting class name. Our class gets username length when it is created. So we need class constructor.

class BadLengthException : public exception {
public:
int N;
BadLengthException(N) {
this->N=N;
};
int what() {
return this->N;
}
}

In the code above our BadLengthException inherited all properties from the exception class. And when this class is initialized, it takes the username length and stores it in public variable N. When the catch block detected exception it will dial with the function what of our exception class to get what is happened.

The one example of this class usage is

#include <iostream>
#include <exception>
using namespace std;
class BadLengthException : public exception {
public:
int N;
BadLengthException(N) {
this->N=N;
};
int what() {
return this->N;
}
}
int main() {
int usernameLength;
cin>>usernameLength;
try {
if(usernameLength<5)
throw BadLengthException(usernameLength);
else
cout<<"Valid";
} catch(BadLengthException e) {
cout<<"Too short: "<<e.what();
}
return 0;
}

--

--