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

Handle Exception using Try, Catch and Throw

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

Try block should contain 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.

C++ Example using try, catch & throw

Output

Exception handling in C++

User Defined Exception

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 exception classes and throw them according to our needs.

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

Output

Try catch throw

In the above C++ Example, we have created empty classes with the relevant error names so that we can throw their objects in the appropriate situation.

Once the thrown object from the try block is caught by any catch block, its corresponding message is displayed.

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

Leave a Reply

Close Menu