What is Exception?

An exception is any unwanted situation which occurs during runtime of the program and which disrupts the smooth flow/running of Program. E.g

IndexOutOfBounds Exception: It occurs when you try to access array element out of its range.

IOException: It occurs when user give wrong input type during runtime e.g String instead of Integer

How to Handle Exceptions?

Exceptions in C++ can be easily handled with the try and catch block with throw keyword.

Try block contains those line of codes which are prone to errors.

Followed by the catch block, catches the error if occurs any in the try block. Catch block parameter can be

  • Single exception type class e.g int &ex, IOException &ex etc
  • Three dots to catch all exception i.e

whereas throw keyword is used to throw the error signal from a try block to catch block.

Note: For Single try block, you can write multiple catch block.

Program Using try, throw & catch


Exception handling in C++

User Defined Exception

The exceptions are nothing but predefined classes in the libraries that comes along the C++ language and are invoked at the time of the specific error. It means that we can create our own exception classes and throw it according to our need.

To create user-defined exception simply create Empty class. The name of the class should be the exception name. E.g

Take a look on the program below to fully understand the use of the user-defined exception.

Program Using User-Defined Exception


Try catch throw

That’s all for exception handling in C++. If you have any doubts then do comment below.

Leave a Reply

Close Menu