- In C++ exception handling is a process to handle runtime errors.
- If we perform exception handling, so the normal flow of the application can be maintained even after runtime errors.
- At run time exception is an event or object which is thrown in C++ and all exceptions are derived from std::exception class.
- It prints exception message and terminates the program, if we don’t handle the exception.
- In C++ exception handling consists of three keywords, they are try, throw, catch
- In exception handling try keyword allows you to define a block of code to be tested for errors when it is being executed.
- In exception handling throw keyword throws an exception when a problem is detected, which lets us create a custom error.
- In exception handling catch keyword allows you to define a block of code to be executed, if an error occurs in the try block.
Syntax
[pastacode lang=”cpp” manual=”%20%20%20%20%20%20%20%20%20%20%20%20%20try%20%7B%0A%20%20%2F%2F%20Block%20of%20code%20to%20try%0A%20%20throw%20exception%3B%20%2F%2F%20Throw%20an%20exception%20when%20a%20problem%20arise%0A%7D%0Acatch%20()%20%7B%0A%20%20%2F%2F%20Block%20of%20code%20to%20handle%20errors%0A%7D%20%0A” message=”” highlight=”” provider=”manual”/]Sample Code
[pastacode lang=”cpp” manual=”try%20%7B%0A%20%20int%20age%20%3D%2015%3B%0A%20%20if%20(age%20%3E%3D%2018)%20%7B%0A%20%20%20%20cout%20%3C%3C%20%22Access%20granted%20-%20you%20are%20old%20enough.%22%3B%0A%20%20%7D%20else%20%7B%0A%20%20%20%20throw%20(age)%3B%0A%20%20%7D%0A%7D%0Acatch%20(int%20myNum)%20%7B%0A%20%20cout%20%3C%3C%20%22Access%20denied%20-%20You%20must%20be%20at%20least%2018%20years%20old.%5Cn%22%3B%0A%20%20cout%20%3C%3C%20%22Age%20is%3A%20%22%20%3C%3C%20myNum%3B%0A%7D%0A” message=”” highlight=”” provider=”manual”/]Output

