|
Oktatás * Programozás 1 * Szkriptnyelvek Teaching * Programming 1 (BI) Félévek Linkek * kalendárium |
Nim2 /
Exception handlingException handling in Nim is very similar to Python. Here is a short example. In an infinite loop, we read two numbers, divide them and print the result. The user can quit with Ctrl+c or Ctrl+d. A lot of things can go wrong; the problems are handled with exceptions. import std/strutils # strip, split, join import std/strformat # &"Hello {name}!" import std/rdstdin # for inputExtra() type ZeroDivisionError = object of CatchableError proc inputExtra(prompt: string = ""): string = var line: string = "" let val = readLineFromStdin(prompt, line) # line is modified if not val: raise newException(EOFError, "abort") line proc main() = while true: try: let a = inputExtra("1st number: ").parseInt b = inputExtra("2nd number: ").parseInt if b == 0: raise newException(ZeroDivisionError, "division by zero") let result: float = a / b echo &"Result: {result:.2f}" except ValueError: echo "Error: provide numbers" except EOFError: # if Ctrl+c or Ctrl+d was pressed echo "bye" break except ZeroDivisionError as e: echo "Error: ", e.msg # Error: division by zero except: # catch anything echo "Error: something went wrong" # echo "---" # ############################################################################ when isMainModule: main() $ ./main 1st number: 5 2nd number: 2 Result: 2.50 --- 1st number: 2 2nd number: hello Error: provide numbers --- 1st number: 2 2nd number: 0 Error: division by zero --- 1st number: <Ctrl+C> bye You can quit from the program with Ctrl+c or Ctrl+d. Create your own exception# create an exception called ZeroDivisionError type ZeroDivisionError = object of CatchableError # throw an exception of this type if b == 0: raise newException(ZeroDivisionError, "division by zero") # catch it and get its message ("division by zero") except ZeroDivisionError as e: echo "Error: ", e.msg # Error: division by zero Links
|
![]() Blogjaim, hobbi projektjeim * The Ubuntu Incident [ edit ] |