C + + Learning Note 13--exception handling

Source: Internet
Author: User

Exception handling

What is an exception: infrequently occurring but unavoidable.

Return error code

Setting errno Global Variables

Throw exception

Catching Exceptions:

Use try{} to wrap the code that might have occurred immediately followed by a number of (at least one) catch (Type E) {} to catch the exception of the specified type and processing, after the program continues to run after the last catch block.

Throw exception: Throw data;

The exception data thrown out by the throw is not limited by the scope of the action until it is processed so that the exception data can be accessed by reference during capture. Even if the exception data has been processed, it can be re-thrown with a throw without data.

If the thrown exception is not caught, the system calls the Terminate () function to terminate the program. Set_terminate (fun) can specify that the Func function is called automatically when terminate.

Exception passing mechanism: from the throw start to leave the normal execution process, in this function to find whether it contains the try{} block, if there is a catch block to find it until the first type match to enter the catch block to perform processing, after the last catch block to continue execution If there is no try{} block or a catch block with no type matching, the exception data continues to be passed to the upper function (the function that called it) to repeat the process, and if it is passed to the kernel until the main function has not been processed, the system will call terminate to terminate the program

Multiple catch Blocks If you have both a parent and subclass type, you should put the class type in front, and if one is a catch (...), it must be at the end.

#include <iostream>using namespacestd; #include<string>voidF1 () {Try{cout<<"1--int\n2--double\n0--return\n"; intN; CIN>>N; if(n==1)Throw 1; if(n==2)Throw 2.2; if(n==0)return; Throw string("Error"); }    Catch(Longe) {cout<<"Long"<<e<<Endl;} Catch(Doublee) {cout<<"Double"<<e<<Endl;} cout<<"----Endl of F1----"<<Endl;}voidF2 () {Try{F1 (); cout<<"----in F2----"<<Endl; }    Catch(inte) {cout<<"int"<<e<<Endl;} cout<<"----End of F2----"<<Endl;}intMain () {Try{F2 (); }    Catch(...) {cout<<"An exception occurred"<<Endl;} cout<<"I'll be back."<<Endl; System ("Pause");}

Exception statement: A function can declare which types of exceptions it might throw, in the form

return type function name (parameter table) throw (Exception type list);

int func (int a[],int idx) throw (double,int,string);

If an exception is thrown inside a function that is not in the list, an unexpected result is thrown. Unexpected can be set by set_unexpected (func) to invoke Func when an unexpected condition is encountered, to set a call to Func when an unexpected condition is encountered. No exception declaration indicates that any type of exception may be thrown, and an empty exception list indicates that no exception is thrown

#include <iostream>using namespacestd; #include<exception>voidF1 (intNThrow(int,Double){    Try{    if(n==1)Throw 123; if(n==2)Throw 4.5; Throw "Out of range"; }    Catch(inte) {cout<<"Catch"<<e<<"In F1"<<Endl; if(e> -)Throw;//To re-throw the current exception data    }}voidFunc () {cout<<"exception type not in List"<<Endl;}intMainintargcChar*argv[]) {//argument parameters, Number of cont, vector indefinite length arrayset_unexpected (func); Try{cout<<"argc="<<argc<<Endl;    F1 (ARGC); }    Catch(inte) {cout<<"int"<<e<<Endl;} Catch(Doublee) {cout<<"Double"<<e<<Endl;} //catch (...) {cout<< "Exception" <<ENDL;}System"Pause");}

Standard Exceptions: Exception class, #include <exception>

When defining a subclass that overrides a virtual function of the parent class, the contents of the exception declaration cannot exceed the contents of the exception declaration in the parent class

Exception types thrown in the standard library are subclasses of exception

Defining the exception type yourself generally inherits the exception class, overriding the Const char* what () const throw () function, returning a string that describes what happened to the exception

    

#include <iostream>using namespacestd; #include<exception>#include<New>#include<cstdio>classa{//Array Class    int*p; intLen; Public:    ExplicitAintNThrow() {p=New(nothrow)int[n]; Len=N; }    int&operator[](intindex) {        if(index<0)ThrowNegindex (index); if(Index>=len)ThrowOutofrange (index); if(P==null)Throwmemoryexception (); returnP[index]; }    classNegindex: Publicexception{inti;  Public: Negindex (intIndexThrow(): I (index) {}; Const Char* What ()Const Throw(){            Static Charbuf[ -]; sprintf (BUF,"negative Subscript Exception%d", i); returnbuf;    }    }; classOutofrange: Publicexception{inti;  Public: Outofrange (intIndexThrow(): I (index) {}; Const Char* What ()Const Throw(){            Static Charbuf[ -]; sprintf (BUF,"crossed%d", i); returnbuf;    }    }; classMemoryexception: Publicexception{ Public:        Const Char* What ()Const Throw(){            return "Not enough memory"; }    };};intMain () {A x (Ten); x[0]  =5, x[3]=Ten, x[8]= -; cout<<x[3]*x[0]*x[8]<<Endl; cout<<x[-5]<<Endl; cout<<x[ -]<<Endl; System ("Pause");}

  

C + + Learning Note 13--exception handling

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.