tmanual_exception.nim 1.2 KB

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