mirror of
https://github.com/nim-lang/Nim.git
synced 2025-12-28 17:04:41 +00:00
ref https://en.cppreference.com/w/cpp/error/exception/what > Pointer to a null-terminated string with explanatory information. The pointer is guaranteed to be valid at least until the exception object from which it is obtained is destroyed, or until a non-const member function on the exception object is called. The pointer is only valid before `CStdException as e` is destroyed Old examples are broken on macOS arm64 ``` /Users/blue/Desktop/nimony/test4.nim(38) test4 /Users/blue/Desktop/nimony/test4.nim(26) fn /Users/blue/.choosenim/toolchains/nim-#devel/lib/std/assertions.nim(41) failedAssertImpl /Users/blue/.choosenim/toolchains/nim-#devel/lib/std/assertions.nim(36) raiseAssert /Users/blue/.choosenim/toolchains/nim-#devel/lib/system/fatal.nim(53) sysFatal Error: unhandled exception: /Users/blue/Desktop/nimony/test4.nim(26, 3) `$b == "foo2"` [AssertionDefect] ```
37 lines
1.1 KiB
Nim
37 lines
1.1 KiB
Nim
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()
|