Previous | Home | Next |
Exception means run time error. To handle run time error, we use exception handling. Exception handling provides us the facility to transfer control from one part of program to another.
To handle run time error we use 3 keywords:-
- Try
- Catch
- Throw
- Try:- Try block contains the code for which exception will occur. This block followed by one or more catch block.
- Catch:- Catch block is use to handle the exception.
- Throw:- Throw keyword is use to raise the unchecked exception. Run time error is thrown by using throw keyword from inside try block.
Syntex:
try { no. of statements and logic } catch (Exception E1) { no. of statements } catch (Exception E2) { no. of statements } catch (Exception En) { no. of statements }
Example:
# include <iostream.h> # include <conio.h> void main () { int a,b,c ; Cout << "Enter the value of variable a"; Cin >> a ; Cout << "Enter the value of variable b"; Cin >> b ; try { c = a/b ; Cout << c ; } else { throw (a/b) ; } catch (exception e) { Cout << "Divide by zero is an error"; } }
Enter the value of variable a 10 Enter the value of variable b 0 Divide by zero is an error
Previous | Home | Next |