First, the steps to read the file:
Each step of the read file operation relies on the implementation of the previous step
Second, code Analysis
1. Traditional error code feedback mechanism
Class Errorcodetypefile{int ErrorCode = 0;if (thefileopened) {Determine it size;if (gotthefilelength) {Allocate that much Memory;if (gotenoughmemory) {Read the file into the Memory;if (readfailed) {errorCode =-1;}} else {errorCode =-2;}} else {ErrorCode =-3;} Close the file;if (thefiledidn ' tclose && errorCode = = 0) {ErrorCode =-4; } else { ErrorCode = ErrorCode and-4; } } else { ErrorCode =-5; } return errorCode;}
With the feedback error code, we can understand which step error occurred, but the code is poor readability, difficult to modify, the logic is not clear.
2. Add code after exception capture mechanism
Try {Open the File;determine its size;allocate, much memory;read the file into the memory;close the file;} catch (file openfailed) {do something;} catch (Sizedeterminedfaile) {does something;} catch (memeoryallocationfailed) {do something;} catch (readfailed) {do something;} catch (fileclosedfailed) {do something;}
After the code adds an exception-catching mechanism, the type of exception can be learned through a catch statement, and the code is highly readable and logically defined, often referred to as the business logic code after the try statement, and after the catch statement is called the exception handling code.
Iii. Summary of today
Java Programming Advanced Path III: exceptions