exception

exception(异常)

int div ( int x , int y ){
    return x / y ;
}
int z = div( 1,0 );
int n;
cin >> n ;
cout << div( 100, n ) << endl;

try-catch 语句

int div ( int x , int y ){
    try{
        return x / y ;
    }catch( DivideByZeroException e){
        cout << e.description << endl ;
    }
}

throw (抛出)语句

int div ( int x , int y ){
    try{
        return x / y ;
    }catch( DivideByZeroException e){
        cout << e.description << endl ;
        throw e;
    }
}
int n;
cin >> n ;
try{
    cout << div( 100, n ) << endl;
}catch( DivideByZeroException e){
    cout << "零不能做除数!" << endl ;
}

可throw任何类型(例如:int)

int div ( int x , int y ){
    try{
        return x / y ;
    }catch( DivideByZeroException e){
        cout << e.description << endl ;
        
        throw 0;
    }
}
int n;
cin >> n ;
try{
    cout << div( 100, n ) << endl;
}catch( int e ){
    cout << "零不能做除数!" << endl ;
}

声明函数可throw的类型

int div ( int x , int y ) throw (int) {
    try{
        return x / y ;
    }catch( DivideByZeroException e){
        cout << e.description << endl ;
        
        throw 0;
    }
}

The End

目录