Finally in Java exception (i)

Source: Internet
Author: User

Tag: Create failed null enhancement str out final NAL lock exception

Finally, the guarantee statement can be executed. Regardless of whether the program will error, we put the program must be executed code in the finally.

For example, the flow is closed, regardless of the process of reading and writing error, be sure to close the stream, you can put the flow of closing operations in finally.

The code shows as follows:

Package exception;

Import Java.io.FileOutputStream;
Import java.io.IOException;


/**
* Finally use in IO
* @author Xiaoming
*
*/
public class FinallyDemo2 {

public static void Main (string[] args) {
The following is the standard flow creation notation
FileOutputStream fos = null;

try {
FOS = new FileOutputStream ("Fos.dat");
Fos.write (1);
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
} finally{
try {
if (fos! = null) {
Fos.close ();
}
Error 1: There is scope, so the definition of the FOS should be placed outside the try, otherwise it will be an error
Error 2:close () method requires handling an exception
Note: It is also possible to make an error during new creation, for example, the path is not correct (the parent path does not exist)
This will create a failure, then the FOS is still empty, then there should be a layer of judgment,
Because the FOS is empty, closing throws an exception.
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}


}

}

This is when the stream is created with standard notation.

Finally in Java exception (i)

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.