Exceptions are the error comes during run time like not able open file, exceeding the array, assign imposition value or shortage of memory. These errors can be handled by three blocks i.e try, throw and catch.
- try: block where exception may generate
- throw: emit the exception
- catch: exception handler
What is the purpose of exception handling ?
If exception happens and we don’t handle it then it will terminate our program (our application) so NO user or developer want an application to be crashed during run time.
Source code with example:
//Header files #include<iostream> void fun() { std::cout<<"fun"<<std::endl; throw 1; //exception will be thrown return; //control wont come here } int main() { std::cout<<"Exception Handling"<<std::endl; try { fun(); } catch(int x) { std::cout<<"Catch Block, value:"<<x<<std::endl; } return 0; }
Output:
Exception Handling fun Catch Block, value:1