0
点赞
收藏
分享

微信扫一扫

C++翁恺学习32-异常基本概念

梦为马 2022-04-26 阅读 60
c++

run-time error

  • the basic philosophy of c++ is that "badly formed code will not be run"
  • there's always something happen in run-time
  • it is very important to deal with all possible situation in the future running

read a file

  • open the file
  • determine its size
  • allocate that much memory
  • read the file into memory
  • close the file
errorCode Type readeFile{
    initialize errorCode = 0;
    open the file;
    if(theFileOpen){
        determine its size;
        if(gotTheFileLength){
            allocate that much memory;
            if(gotEnoughMemoty){
                read the file into memory;
                if(readFailed){
                    errorCode = -1;
                }
            }else{
                errorCode = -2;
            }
        }else{
            errorCode = -3;
        }
        close the file;
        if(theFIEDidntClose&&errorCode ==0){
            errorCode = -4;
        }else{
            errorCode = errorCode and -4;
        }
    }else{
        errorCode = -5;
    }
    return errorCode;
}

working w/exception  

try{
    open the file;
    determine its size;
    allocate that much memory;
    read the file into memory;
    close the file;
}catch(fileOpenFailed){
    doSomting;
}catch(sizeDeterminationFailed){
    doSomting;
}catch(memoryAllocationFailed){
    doSomting;
}catch(readFailed){
    doSomting;
}catch(fileCloseFailed){
    doSomting;
}

exception

  • I take exception to that
  • At the point where the problem occurs,you might not known what to do with it,but you do know that you can't just continue on merrily;you must stop ,and somebody,somewhere,must figure out what to do

why exception? 清晰

  • the significant benefit of exceptions is that they clean up error handing code  
  • it separates the code that describes what you want to do from the code that is executed
举报

相关推荐

0 条评论