diff options
-rw-r--r-- | lib/pure/streams.nim | 10 | ||||
-rw-r--r-- | tests/stdlib/tstreams3.nim | 10 |
2 files changed, 20 insertions, 0 deletions
diff --git a/lib/pure/streams.nim b/lib/pure/streams.nim index 354e07da3..025a534c5 100644 --- a/lib/pure/streams.nim +++ b/lib/pure/streams.nim @@ -447,9 +447,19 @@ when not defined(js): ## creates a new stream from the file named `filename` with the mode `mode`. ## If the file cannot be opened, nil is returned. See the `system ## <system.html>`_ module for a list of available FileMode enums. + ## **This function returns nil in case of failure. To prevent unexpected + ## behavior and ensure proper error handling, use openFileStream instead.** var f: File if open(f, filename, mode, bufSize): result = newFileStream(f) + proc openFileStream*(filename: string, mode: FileMode = fmRead, bufSize: int = -1): FileStream = + ## creates a new stream from the file named `filename` with the mode `mode`. + ## If the file cannot be opened, an IO exception is raised. + var f: File + if open(f, filename, mode, bufSize): + return newFileStream(f) + else: + raise newEIO("cannot open file") when true: discard diff --git a/tests/stdlib/tstreams3.nim b/tests/stdlib/tstreams3.nim new file mode 100644 index 000000000..b2c9170e3 --- /dev/null +++ b/tests/stdlib/tstreams3.nim @@ -0,0 +1,10 @@ +discard """ + file: "tstreams3.nim" + output: "threw exception" +""" +import streams + +try: + var fs = openFileStream("shouldneverexist.txt") +except IoError: + echo "threw exception" |