Search code examples
c++exceptioncustom-exceptions

Custom Exception Class - Why do we need it?


I was reading about custom exception.. This is what I did.

#include <iostream>
#include <exception>
#include <stdexcept>

using namespace std;

class myBase : public exception
{
public:
    myBase() {};
    virtual ~myBase(void) {};
    virtual const char* what() const { return "Hello, you have done a mistake"; }
};

class myDerived : public myBase
{
public:
    myDerived() {};
    virtual ~myDerived(void) {};
    const char* what() const { return "Hello, you have done a mistake in - derived class"; }
};

int main(void)
{
    try
    {
        throw myDerived();
    }
    catch (exception& e)
    {
        cout << e.what() << endl;
    }

    getchar();
    return 0;
}

I understood that, I can throw my custom class objects and can catch it. I don't understand the purpose of this. Can someone explain me why do we need custom exception class? Any practical examples will help me understanding the purpose of using custom exception classes.

Thanks.


Solution

  • Lets say that there's also another user defined class that also inherits from class myBase:

    class myDerived2 : public myBase {
    public:
        myDerived2() {}
        virtual ~myDerived2() {}
    };
    

    and lets say that you have a try catch clause:

    try {
      myDerived  A;
      myDerived2 B;
      ...
      /* to staff with both A and B */
      ...
    } catch (std::exception& e){
      cout << e.what() << endl; 
    }
    
    • In the above try - catch clause you restrict your self by treating exceptions of type myDerived and myDerived2 in identical way.

    • What if you wanted to treat throws of type myDerived and myDerived2 in a different way?

    • Then you would have to define a different try-catch clause:


    try {
      myDerived  A;
      myDerived2 B;
      ...
      /* to staff with both A and B */
      ...
    } catch (myDerived &d1) {
      /* treat exception of type myDerived */
    } catch (myDerived &d2) {
      /* treat exception of type myDerived2 */
    }
    
    • From the above example I think it's clear that defining custom exceptions gives the programmer a valuable and versatile tool for dealing with throws in a more versatile and specialized manner.