异常机制的作用

1.更正常代码分离

比如读取一个文件到内存: readFile { open the file; determine its size; allocate that much memory; read the file into memory; close the file; } 但是这些过程可能会出现哪些异常呢 1.文件找不到 2.文件大小检测不出或者太大 3.文件太大分配内存失败 4.读取文件到内存时失败 5.关闭文件时失败

按照传统的方法处理的话,处理这些问题 代码应该这样:

errorCodeType readFile { initialize errorCode = 0; open the file; if (theFileIsOpen) { determine the length of the file; if (gotTheFileLength) { allocate that much memory; if (gotEnoughMemory) { read the file into memory; if (readFailed) { errorCode = -1; } } else { errorCode = -2; } } else { errorCode = -3; } close the file; if (theFileDidntClose && errorCode == 0) { errorCode = -4; } else { errorCode = errorCode and -4; } } else { errorCode = -5; } return errorCode; }

而采用异常制作 代码就简单多了

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

向上传递错误

比这样四个方法:

method1 { call method2; } method2 { call method3; } method3 { call readFile; }

假如只有method1 对readFile产生的错误感兴趣的话,按照传统方法就要求method2 和method3 返回 readFile的错误代码,而这个处理对method2和method3来说没有意义

method1 { errorCodeType error; error = call method2; if (error) doErrorPRocessing; else proceed; } errorCodeType method2 { errorCodeType error; error = call method3; if (error) return error; else proceed; } errorCodeType method3 { errorCodeType error; error = call readFile; if (error) return error; else proceed; }

改用异常机制后:

method1 { try { call method2; } catch (exception e) { doErrorProcessing; } } method2 throws exception { call method3; } method3 throws exception { call readFile; }

3.区分和分组各种错误

比如上面readFile方法,如果不在乎会出那种问题的话 就直接写成:

// A (too) general exception handler catch (Exception e) { ... }

不过还是建议针对对不同的异常,进行不同的处理,才能找到更好的恢复异常的方案。比如某个注册功能 是提醒系统错误还是提醒 用户名已经注册 电话号码不合法的好。