Recent Changes - Search:

Oktatás

* Programozás 1
  + feladatsor
  + GitHub oldal

* Szkriptnyelvek
  + feladatsor
  + quick link

Teaching

* Programming 1 (BI)
  ◇ exercises
  ◇ quick link

teaching assets


Félévek

* 2025/26/2
* archívum


Linkek

* kalendárium
   - munkaszüneti napok '20
* tételsorok
* jegyzetek
* szakdolgozat / PhD
* ösztöndíjak
* certificates
* C lang.
* C++
* C#
* Clojure
* D lang.
* Java
* Nim
* Nim2
* Scala


[ edit | logout ]
[ sandbox | passwd ]

Exception handling

Exception 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

Cloud City

  

Blogjaim, hobbi projektjeim

* The Ubuntu Incident
* Python Adventures
* @GitHub
* heroku
* extra
* haladó Python
* YouTube listák


Debrecen | la France


[ edit ]

Edit - History - Print *** Report - Recent Changes - Search
Page last modified on 2026 April 08, 07:32