Java Programming Advanced Path III: exceptions

Source: Internet
Author: User

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

Related Article

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.