* refs #14369 improve docs for importcpp exceptions * address comments
This commit is contained in:
parent
810039ec0b
commit
2627e1e945
1 changed files with 28 additions and 6 deletions
|
|
@ -4247,16 +4247,38 @@ It is possible to raise/catch imported C++ exceptions. Types imported using
|
||||||
caught by reference. Example:
|
caught by reference. Example:
|
||||||
|
|
||||||
.. code-block:: nim
|
.. code-block:: nim
|
||||||
|
:test: "nim cpp -r $1"
|
||||||
|
|
||||||
type
|
type
|
||||||
std_exception {.importcpp: "std::exception", header: "<exception>".} = object
|
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 what(s: std_exception): cstring {.importcpp: "((char *)#.what())".}
|
proc fn() =
|
||||||
|
let a = initRuntimeError("foo")
|
||||||
|
doAssert $a.what == "foo"
|
||||||
|
var b: cstring
|
||||||
|
try: raise initRuntimeError("foo2")
|
||||||
|
except CStdException as e:
|
||||||
|
doAssert e is CStdException
|
||||||
|
b = e.what()
|
||||||
|
doAssert $b == "foo2"
|
||||||
|
|
||||||
try:
|
try: raise initStdException()
|
||||||
raise std_exception()
|
except CStdException: discard
|
||||||
except std_exception as ex:
|
|
||||||
echo ex.what()
|
try: raise initRuntimeError("foo3")
|
||||||
|
except CRuntimeError as e:
|
||||||
|
b = e.what()
|
||||||
|
except CStdException:
|
||||||
|
doAssert false
|
||||||
|
doAssert $b == "foo3"
|
||||||
|
|
||||||
|
fn()
|
||||||
|
|
||||||
**Note:** `getCurrentException()` and `getCurrentExceptionMsg()` are not available
|
**Note:** `getCurrentException()` and `getCurrentExceptionMsg()` are not available
|
||||||
for imported exceptions. You need to use `except ImportedException as x:` syntax
|
for imported exceptions. You need to use `except ImportedException as x:` syntax
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue