html5-img
1 / 6

Exceptions in C++

Exceptions in C++. Exceptions. Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.

azure
Download Presentation

Exceptions in C++

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Exceptions in C++

  2. Exceptions • Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers. • To catch exceptions we have to place our code on which we want exception handling in the try block. If an exception occurs the control is passed to the handler, otherwise the handlers are ignored. • The code to be executed, that may produce exceptions, is placed in the try block and the error handlers are declared with the keyword catch.

  3. Example • First Example #include <iostream> using namespace std; int main () { try { throw 10; } catch (int e) { cout << “We have a problem!!” << endl; } return 0; } Output : We have a problem!!!

  4. Throw • The throw expression accepts one parameter as its argument and this is passed to the exception handler. You can have a number of throw statements at different parts of your try block with different values being thrown so that the exception handler on receiving the parameter will know what restorative actions to take. try { // code if ( x ) throw 10; // code if (y) throw 20; //code }

  5. Catch() {} • The exception handler can be identified by the keyword catch . catch always takes only one parameter. The type of the catch parameter is important as the type of the argument passed by the throw expression is checked against it and the catch function with the correct parameter type is executed. This way we can chain multiple exception handlers and only the one with the correct parameter type gets executed. • The catch(…) handler catches all exceptions, no matter what type. It can be used as a default handler if declared last. try { // code here } catch (int param) { cout << "int exception"; } catch (char param) { cout << "char exception"; } catch (...) { cout << "default exception"; }

  6. Some Points to remember • You can nest the try-catch blocks. • After exception handling the program returns to the point after the try-catch block, not after the throw statement.

More Related