Advertisement
Guest User

Untitled

a guest
Jan 23rd, 2017
752
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.07 KB | None | 0 0
  1. #include "stdafx.h"
  2. #include <iostream>
  3. #include <exception> // biblioteka "z wyjątkami"
  4.  
  5. using namespace std;
  6.  
  7. int fun(int a, int b); // prototyp funkcji
  8.  
  9. int main()
  10. {
  11.     int dzielna;
  12.     int dzielnik;
  13.     cout << "podaj dzielna: ";  // wiadomo
  14.     cin >> dzielna;
  15.     cout << "podaj dzielnik: ";
  16.     cin >> dzielnik;
  17.  
  18.     try
  19.     {
  20.         cout << fun(dzielna, dzielnik) << endl; // wywołujemy funkcję, jeśli dzielnik będzie równy 0 to funkcja "fun" rzuci wyjątkiem
  21.        
  22.     }
  23.     catch (exception ex) // w tym miejscu przechwytujemy wyjątek (nadajemu mu nazwę "ex")
  24.     {
  25.         cout << "Error: " << ex.what() << endl; // wyświetlamy wyjątek (samo ex.what() wystarczy ale dodałem Error żeby wyglądało very profeszynal)
  26.     }
  27.  
  28.     system("pause");
  29.     return 0;
  30. }
  31.  
  32. int fun(int a, int b)
  33. {
  34.     if (b == 0) throw exception("Dzielnik rowny 0!!!"); // na początku działania funkcji sprawdzamy, czy dzielnik jest równy 0, jeśli jest, to "rzucamy wyjątkiem", który informuje nas, że zaszło dzielenie przez 0
  35.     return a / b; // zwracamy wynik dzielenia w wypadku gdy dzielnik nie jest równy 0
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement