When things go wrong
Files go missing, text is not a number, networks fail. This lesson shows how .NET reports problems, how to catch them, and how to write programs that handle them calmly.
What you will learn#
- what an exception is and how Ring shows it,
try/catchand reading the error text,- asking first (
Exists,TryParse) instead of catching, - raising your own errors,
- cleaning up even when something fails.
Exceptions#
When .NET cannot do what you asked, it throws an exception: it stops the normal flow and reports the problem. In Ring a .NET exception is a Ring error. Without try, it ends your program with a message. With try ... catch you decide what happens.
try
new Int32().Parse("abc")
catch
? cCatchError
donecCatchError holds the message. It starts with DotNet Error: followed by the name of the exception (System.FormatException) and an explanation. The name tells you the kind of problem.
The program#
# when things go wrong - exceptions, try/catch, checking before you act
load "dotnet.ring"
using {
"System"
"System.IO"
}
func main
# A .NET exception becomes a Ring error you can catch
try
new Int32().Parse("abc")
? "this line is never reached"
catch
? "1. Caught the error:"
? " " + cCatchError
done
# The text of the error names the .NET exception type: you can react to the kind of error
try
new File().ReadAllText("c:\this\file\does\not\exist.txt")
catch
if substr(cCatchError,"FileNotFoundException") > 0 or substr(cCatchError,"DirectoryNotFoundException") > 0
? "2. The file is missing"
else
? "2. Some other error: " + cCatchError
ok
done
# Often it is better to ask first than to catch
cName = "c:\this\file\does\not\exist.txt"
if new File().Exists(cName)
? "3. Reading it"
else
? "3. Exists() said no: no error at all"
ok
# TryParse tells you in the result instead of raising an error
aNumber = new Int32().TryParse("12x")
if aNumber[1]
? "4. A number"
else
? "4. Not a number: TryParse returned false"
ok
# Your own errors: raise() creates one, the caller catches it
try
withdraw(100,250)
catch
? "5. " + cCatchError
done
# Clean up in every case: do it after the try block
oWriter = ""
try
cFile = new Path().Combine([new Path().GetTempPath(),"ringdotnet_errors.txt"])
oWriter = new StreamWriter(cFile)
oWriter.WriteLine("some text")
new Int32().Parse("oops")
catch
? "6. Error while writing: the file will still be closed"
done
if isobject(oWriter)
oWriter.Close()
new File().Delete(cFile)
? " closed and deleted the file"
ok
# More detail while you are developing: set RINGDOTNET_TRACE=1 to see the .NET stack trace in the error text
func withdraw nBalance, nAmount
if nAmount > nBalance
raise("Not enough money: balance " + nBalance + ", asked " + nAmount)
ok
return nBalance - nAmount1. Caught the error:
DotNet Error: System.FormatException: The input string 'abc' was not in a correct format.
2. The file is missing
3. Exists() said no: no error at all
4. Not a number: TryParse returned false
5. Not enough money: balance 100, asked 250
6. Error while writing: the file will still be closed
closed and deleted the fileHow it works#
1. Catch the error#
The first block shows the message: System.FormatException: The input string 'abc' was not in a correct format.
2. React to the kind of error#
substr(cCatchError,"FileNotFoundException") > 0 asks if the name appears in the text. Different problems get different answers: a missing file may be told to the user; a full disk may stop the program.
3. Ask first#
Catching is for the unexpected. If you can check a condition, do that: File.Exists(cName) returns false instead of raising an error. It is shorter, faster and clearer.
4. TryParse#
The same idea for numbers. TryParse returns [worked, value]; you decide.
5. Your own errors#
raise("text") creates an error. Use it when your function is called with a request it cannot honor (withdraw(100,250)). The caller sees the text in cCatchError.
6. Clean up#
Open files, connections and readers must be closed even when an error happens. The simple pattern: put the work in try, and do the cleanup after the try block. The program checks if the writer exists, closes it and deletes the file.
More detail#
While developing, set the environment variable RINGDOTNET_TRACE=1 and the error text includes the .NET stack trace, which shows exactly where it happened.
Good habits#
| Do | Do not |
|---|---|
check with Exists, TryParse, IsNullOrWhiteSpace first | wrap the whole program in one try |
| catch where you can do something about it | catch and ignore |
| show a friendly message, log the technical one | show cCatchError to end users |
| close what you open | leave files open |
What you learned#
- a .NET exception is a Ring error, and
try/catchhandles it, cCatchErrorstarts with the name of the exception, which tells the kind of problem,- ask first (
Exists,TryParse) when you can, raise("text")makes your own error,- clean up after the
tryblock.
Exercises#
- Write
readNumber(cText)that returns the number, or-1if the text is not a number, usingTryParse. - Read a file that may not exist: print
missingif it does not, the number of lines if it does. Do it twice: once withExists, once withtry. - Write
divide(a,b)that raises"Division by zero"whenbis 0, and catch it. - Cause a
DirectoryNotFoundException: write a file into a folder that does not exist. Read the message.