以下代码段在已创建数据库时有效,但在未创建数据库时失败。对我来说,更令人担忧的问题是我的代码不捕获代码在未创建数据库时抛出的错误。我是Ocaml错误处理的新手,所以我想知道为什么这不起作用。这是我收到的错误:
Fatal error: exception Postgresql.Error(_)
这是我的代码:
open Postgresql;;
let main () = (
let c = new connection ~host:"localhost" ~port:"5432" ~dbname:"stocks" ~user:"postgres"
~password:"postgres" () in
let status () = (
try match c#status with
| Ok -> print_string ("STATUS CONNECTED\n");
| Bad -> print_string "BAD";
with Error(s) ->( print_string (string_of_error(s)))) in
status();
c#finish
);;
main();;
答案 0 :(得分:0)
很可能在let c = ....
语句中引发异常,因为它不在try....with
块内。下面的代码示例并不理想,但比您拥有更多的OCaml方式。
open Postgresql
let with_connection f =
try
let c = new connection ~host:"localhost" ~port:"5432" ~dbname:"stocks" ~user:"postgres"
~password:"postgres" () in
f c;
c#finish
with _ -> print_endline "ERROR"
let main () =
with_connection (fun c ->
try match c#status with
| Ok -> print_string ("STATUS CONNECTED\n");
| Bad -> print_string "BAD";
with Error(s) ->( print_string (string_of_error(s))))
)
let () = main ()