The basics of programming in c++ for beginners

Exceptions in c++

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 the division number to 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 vardecremented via decrement. But as we just have value 0 in a variablenum2, 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– blockthrow(handle, run);

 

  • exception handler, which it intercepts -command catch (to catch, catch)

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

Example:

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: ifnum2 will be equal to 0, then letthrow generates a number 999 (for example).

In that case, immediately after generating a number, further commands in the blocktry will no longer be performed, and the sheer number “fall” in blockcatch (as a parameter). Next, execute the, as indicated in blockcatch – 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 ofnum2 != 0, then throw nothing generates and catch-unit does not work.

Look now, how to react to the program, if you typenum2 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 fulfilledcatch-block.

To help you better understand, as the value generatedthrow interceptscatch-block, replace the code in strings 21 – 33 on this:

In this example,, if num2 is 0,throw generates a string, and not the number. String “falls” incatch-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 blocktry:

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

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

    • Attry-block (retries block) you must place the code, which could potentially lead to the closure of the emergency program;

 

    • An exception is generated at blockthrow. Ifthrow work program will automatically proceed to the execution of commandscatch-block, ignoring the rest of the code in try-block;

 

    • The trap block – catch-block, intercepts the, that generates a blockthrow. He must be undertry-block. Nothing should be written between them;

 

  • catch-unit does not work, if the exception were not generated. The program will simply ignore it.

9 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?

    #include
    #include
    #include // содержит time()
    using namespace std;

    int main()
    {
    setlocale(LC_ALL, "rus");

    int s1 = 0;
    int s2 = 0;
    char exit = 1;
    int over = 0;

    cout <<
    "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
    cout << " Делите только у нас !!! \n";
    cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
    do
    {
    cout << "\n ~~~~~~~~~~ Введите ваши числа: ~~~~~~~~~~ \n";
    cout < ";
    cin >> s1;
    cout < ";
    cin >> s2;
    try
    {
    over = s1 / s2;
    cout < " << over << endl;
    cout << "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
    cout << " Для продолжения вычислений нажми - 1, Для выхода - 0 \n";
    cout << exit;
    throw 999;
    }
    catch (int thr)
    {
    cout << "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
    cout << " ~~~~~~~~ Похоже ты допустил ошибку!!! ~~~~~~~~ ";
    cout << "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
    }
    } while (exit != 0);
    return 0;
    }

    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:
      catch( exception const& e ) {

  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.

    1. 1). It is necessary to indicate which online compiler – a lot of them, and there are quite a priduryu…
      2). Different standards of C ++ (for example, C ++ 11) syntax records a try {} catch – may differ;
      3). Many online compilers (best) allow you to specify the standard C ++ language, which will be used in the code;

  4. For those who do not have the code above, use this:

    #include
    using namespace std;
    int main()
    {
    setlocale(LC_ALL, “rus”);

    int num1;
    int num2;

    int var = 3;
    while (var != 0)
    {
    cout <> num1;
    cout <> num2;

    cout << "num1 + num2 = " << num1 + num2 << endl;
    cout << "num1 / num2 = ";

    try // тут располагается код, который потенциально может вызвать ошибку
    {
    if (num2 == 0)
    {
    throw 999; // генерировать целое число 999
    }
    cout << num1 / num2 << endl;
    }

    catch (int thr)// сюда передастся число, которое сгенерировал throw
    {
    cout << "Ошибка №" << thr << " – division by 0!!!" << endl;
    }

    cout << "num1 – num2 = " << num1 – num2 << endl;
    cout << "=================================" << endl << endl;

    var–;
    }

    cout << "Программа завершила работу!" << endl << endl;

    return 0;
    }

  5. First payment policy =>> https://forms.yandex.ru/cloud/6547f88bd04688f1a57043ac/?hs=d54bc26c72a533a0d5ffd6e60e6a4215& # MZ089 says:

    77el3m

Leave a Reply

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