tmanual_exception.nim 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. discard """
  2. targets: cpp
  3. """
  4. # manual example
  5. type
  6. CStdException {.importcpp: "std::exception", header: "<exception>", inheritable.} = object
  7. ## does not inherit from `RootObj`, so we use `inheritable` instead
  8. CRuntimeError {.requiresInit, importcpp: "std::runtime_error", header: "<stdexcept>".} = object of CStdException
  9. ## `CRuntimeError` has no default constructor => `requiresInit`
  10. proc what(s: CStdException): cstring {.importcpp: "((char *)#.what())".}
  11. proc initRuntimeError(a: cstring): CRuntimeError {.importcpp: "std::runtime_error(@)", constructor.}
  12. proc initStdException(): CStdException {.importcpp: "std::exception()", constructor.}
  13. proc fn() =
  14. let a = initRuntimeError("foo")
  15. doAssert $a.what == "foo"
  16. var b = ""
  17. try: raise initRuntimeError("foo2")
  18. except CStdException as e:
  19. doAssert e is CStdException
  20. b = $e.what()
  21. doAssert b == "foo2"
  22. try: raise initStdException()
  23. except CStdException: discard
  24. try: raise initRuntimeError("foo3")
  25. except CRuntimeError as e:
  26. b = $e.what()
  27. except CStdException:
  28. doAssert false
  29. doAssert b == "foo3"
  30. fn()