Exceptions in c++

exceptions in c ++, c ++ exceptions, Programming for beginners

Sometimes, during the operation of applications, there are situations that hinder further their normal work. For example, by dividing the number of zero, the program will work in spite of the fact, How many user worked in the programme, and how much data is made. The program simply closes. And imagine, if brought before the user program data and a few hours spent calculations. In such an emergency closure of the program, all the data and calculations will be lost. Agree – not very nice. May also meet this situation, when a program is trying to open is not available at this moment file, or request more, than available memory.

This kind of situation, programmers must try to anticipate and build programs, that they are able to respond flexibly to, rather than emergency close. In my favorite book The C ++ language programming. Lectures and exercises From the author. Prata, given the following definition of exceptions in C ++:

exceptions in c ++, c ++ exceptions, Programming for beginners

To you it is not difficult to understand the mechanism of exceptions in c++, Let's take a simple example. In it, we foresee the case, that at some point during the program calculations, can meet on the division of 0. Type and compile the code, located below the. To make sure, how the program responds to this situation, enter the number of 0 in a variable num2 (it acts as the divider in the example).

Because the variable var is 3, loop while, in normal situation, must work three times. With each step of the loop var decremented via decrement. But as we just have value 0 in a variable num2, the program does not take place before the end of even the first step of the loop. It will break.

The following listing, we will correct this omission – add a few components, to help respond to this situation without interrupting programs. Namely:

  • block try or try-block (attempt, sample);
  • exceptions generator – block throw (handle, run);
  • exception handler, which it intercepts -command catch (to catch, catch)

How does an exception? – The programmer registers in the code (in try-block) specific condition, what if the variable num2 will be equal to 0, in that case you need to generate an exception throw. Further, what generated throw, intercepts catch-block (as a function of the parameter) and the program will execute the code, which is registered in this block.


Understand in detail. In strings 21-29 unit is try. You must place the code, which can lead to irreversible errors. Even before the arithmetic expression dividing the set condition: if num2 will be equal to 0, then let throw generates a number 999 (for example). In that case, immediately after generating a number, further commands in the block try will no longer be performed, and the sheer number “fall” in block catch (as a parameter). Next, execute the, as indicated in block catch – in our case, this is an error message:

cout << "Ошибка №" << thr << " - division by 0!!!" << endl;

and the program will execute the following commands. In that case, if the number of num2 != 0, then throw nothing generates and catch-unit does not work.

Look now, how to react to the program, if you type num2 equal to zero. Run the program.

exceptions in c ++, c ++ exceptions, Programming for beginners

As you can see, where there could be an error and the early completion of the program, we saw a message Error №999 – division by 0!!! Program “leaped” through the division operation on 0 and fulfilled catch-block.

To help you better understand, as the value generated throw intercepts catch-block, replace the code in strings 21 – 33 on this:

In this example,, if num2 equal to 0, throw generates a string, and not the number. String “falls” in catch-block and displayed on screen.

Let's look at an example, when an exception is generated functions, divides one number by another number:

To the exclusion worked properly, this feature is necessary to call in the block try:

catch the number of intercepts 99, and dividing by 0 not be held.

Main, what you need to remember about exceptions in c++:

  • At try-block (retries block) you must place the code, which could potentially lead to the closure of the emergency program;
  • An exception is generated at block throw. If throw work program will automatically proceed to the execution of commands catch-block, ignoring the rest of the code in try-block;
  • The trap block – catch-block, intercepts the, that generates a block throw. He must be under try-block. Nothing should be written between them;
  • catch-unit does not work, if the exception were not generated. The program will simply ignore it.
Newsletter of programming:

Exceptions in c++
3.7 (73.33%) 3 votes

6 thoughts on “Exceptions in c++

  1. Actually, Topic exceptions in any programming language – quite slippery. This mechanism makes its advantages, and disadvantages and the use of hidden dangers.
    The C ++ language – proizvodnыy than C, and in this development included the elimination. Next development (2008-2009GG) C language – This language Go. From this exception, we were excluded and developers with a very thorough published arguments why they did it.
    Reyume: C ++ exceptions need to use, but there, where they are essential, where their use was unavoidable. In other cases it is better to use the traditional return of the error code.

  2. Help the good people!!! What is wrong with a try I?

    1. And you have to throw it does not reach – crash occurs earlier, when divided by 0.

      And catch parameter should be something, inherited from class Exception:

  3. Hello. You have an error in the third Listing.

    cout << num1 / num2 << endl; //We need to withdraw beyond the if statement. otherwise it does not work.

  4. Онлайн компилятор вообще не компилирует код с “try” etc. … – показывает ошибку

    1. 1). Нужно указывать КАКОЙ онлайн компилятор – a lot of them, и есть совсем с придурью
      2). В разных стандартах C++ (например C++11) синтаксис записи блока try {} catch – может отличаться;
      3). Многие онлайн компиляторы (лучшие) позволяют указать тот стандарт языка C++, который будет использоваться в коде;

Leave a Reply

Your email address will not be published. Required fields are marked *