Skip to content

Commit 6c0d2bd

Browse files
committed
Add example without defer statement
1 parent 25f9078 commit 6c0d2bd

File tree

2 files changed

+35
-3
lines changed

2 files changed

+35
-3
lines changed

go/ql/src/InconsistentCode/UnhandledCloseWritableHandle.qhelp

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,11 +21,21 @@ Always check whether <code>os.File.Close</code> returned an error and handle it
2121
</recommendation>
2222

2323
<example>
24+
25+
<p>
26+
In this first example, two calls to <code>os.File.Close</code> are made with the intention of
27+
closing the file after all work on it has been done or if writing to it fails. However, while
28+
errors that may arise during the call to <code>os.File.WriteString</code> are handled, any
29+
errors arising from the calls to <code>os.File.Close</code> are discarded silently:
30+
</p>
31+
32+
<sample src="UnhandledCloseWritableHandleNotDeferred.go" />
33+
2434
<p>
25-
In the following example, a call to <code>os.File.Close</code> is deferred with the intention of
26-
closing the file after all work on it has been done. However, while errors that may arise during
35+
In the second example, a call to <code>os.File.Close</code> is deferred in order to accomplish
36+
the same behaviour as in the first example. However, while errors that may arise during
2737
the call to <code>os.File.WriteString</code> are handled, any errors arising from
28-
<code>os.File.Close</code> are discarded silently:
38+
<code>os.File.Close</code> are again discarded silently:
2939
</p>
3040

3141
<sample src="UnhandledCloseWritableHandle.go" />
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package main
2+
3+
import (
4+
"os"
5+
)
6+
7+
func example() error {
8+
f, err := os.OpenFile("file.txt", os.O_WRONLY|os.O_CREATE, 0666)
9+
10+
if err != nil {
11+
return err
12+
}
13+
14+
if _, err := f.WriteString("Hello"); err != nil {
15+
f.Close()
16+
return err
17+
}
18+
19+
f.Close()
20+
21+
return nil
22+
}

0 commit comments

Comments
 (0)