summary refs log tree commit diff stats
path: root/doc
diff options
context:
space:
mode:
authorTimothee Cour <timothee.cour2@gmail.com>2020-05-18 09:10:30 -0700
committerGitHub <noreply@github.com>2020-05-18 17:10:30 +0100
commit2627e1e9459379c9bc180890980e571ad7adf203 (patch)
tree083a4cfc2d24df98fcbe9151e463f521583f4ea5 /doc
parent810039ec0b394a952af319616f7da0abfee5d812 (diff)
downloadNim-2627e1e9459379c9bc180890980e571ad7adf203.tar.gz
refs #14369 improve docs for importcpp exceptions (#14391)
* refs #14369 improve docs for importcpp exceptions

* address comments
Diffstat (limited to 'doc')
-rw-r--r--doc/manual.rst38
1 files changed, 30 insertions, 8 deletions
diff --git a/doc/manual.rst b/doc/manual.rst
index 80029fca4..759042078 100644
--- a/doc/manual.rst
+++ b/doc/manual.rst
@@ -4247,16 +4247,38 @@ It is possible to raise/catch imported C++ exceptions. Types imported using
 caught by reference. Example:
 
 .. code-block:: nim
+    :test: "nim cpp -r $1"
 
   type
-    std_exception {.importcpp: "std::exception", header: "<exception>".} = object
-
-  proc what(s: std_exception): cstring {.importcpp: "((char *)#.what())".}
-
-  try:
-    raise std_exception()
-  except std_exception as ex:
-    echo ex.what()
+    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: cstring
+    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()
 
 **Note:** `getCurrentException()` and `getCurrentExceptionMsg()` are not available 
 for imported exceptions. You need to use `except ImportedException as x:` syntax