File: tmanual_exception.nim

package info (click to toggle)
nim 2.2.4-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,951,164 kB
  • sloc: sh: 24,599; ansic: 1,771; python: 1,493; makefile: 1,013; sql: 298; asm: 141; xml: 13
file content (36 lines) | stat: -rw-r--r-- 1,114 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
discard """
  targets: cpp
"""

# manual example

type
  CStdException {.importcpp: "std::exception", header: "<exception>", inheritable.} = object
    ## does not inherit from `RootObj`, so we use `inheritable` instead
  CRuntimeError {.requiresInit, importcpp: "std::runtime_error", header: "<stdexcept>".} = object of CStdException
    ## `CRuntimeError` has no default constructor => `requiresInit`
proc what(s: CStdException): cstring {.importcpp: "((char *)#.what())".}
proc initRuntimeError(a: cstring): CRuntimeError {.importcpp: "std::runtime_error(@)", constructor.}
proc initStdException(): CStdException {.importcpp: "std::exception()", constructor.}

proc fn() =
  let a = initRuntimeError("foo")
  doAssert $a.what == "foo"
  var b = ""
  try: raise initRuntimeError("foo2")
  except CStdException as e:
    doAssert e is CStdException
    b = $e.what()
  doAssert b == "foo2"

  try: raise initStdException()
  except CStdException: discard

  try: raise initRuntimeError("foo3")
  except CRuntimeError as e:
    b = $e.what()
  except CStdException:
    doAssert false
  doAssert b == "foo3"

fn()