Exception Handling


  • During the development of a program, there may be some cases where we do not have the certainty that a piece of the code is going to work right, either because it accesses resources that do not exist or because it gets out of an expected range, etc...
  • These types of situations can be handled by exceptions and C++ provides three keywords for it try, throw and catch.
  • Syntax:
    try {
     //code to be tried 
    throw exception;
    }
    catch (type exception)
    {
    //code to be executed in case of exception
    }
    Operation:
  • The code within the try block is executed normally, In case that an exception takes place, this code must use the throw keyword and a parameter to throw an exception. The type of the parameter details the exception and can be of any valid type.
  • If an exception has taken place, that is to say, if it has executed a throw instruction within the try block, the catch block is executed receiving as parameter the exception passed by throw.

  • Output

    Exception: Out of range
  • It is also possible to nest try-catch blocks within more external try blocks. In these cases, we have the possibility that an internal catch block forwards the exception received to the external level, for that the expression throw; with no arguments is used. For example:
    click here for Example1
    Example2

    Exceptions not caught

    • If an exception is not caught by any catch statement because there is no catch statement with a matching type, the special function terminate will be called.
    • This function is generally defined so that it terminates the current process immediately showing an "Abnormal termination" error message.
    • Its format is: void terminate( );

    Parameter values for templates<< Previous
    Next >> Graphics in C++

    Our aim is to provide information to the knowledge seekers. 


    comments powered by Disqus






  • Footer1