octave-maintainers
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

try/catch in C++ code


From: John W. Eaton
Subject: try/catch in C++ code
Date: Thu, 23 Jul 2009 15:18:18 -0400

In the change I just checked in, I wrote a function that did the
equivalent of try/catch, but in C++ code.  I wrote it this way
(compare with tree_evaluator::visit_try_catch_command in
src/pt-eval.cc):

  static octave_value
  safe_symbol_lookup (const std::string& symbol_name)
  {
    octave_value retval;

    unwind_protect::frame_id_t uwp_frame = unwind_protect::begin_frame ();

    unwind_protect::protect_var (buffer_error_messages);
    unwind_protect::protect_var (Vdebug_on_error);
    unwind_protect::protect_var (Vdebug_on_warning);

    buffer_error_messages++;
    Vdebug_on_error = false;
    Vdebug_on_warning = false;

    retval = symbol_table::find (symbol_name);

    error_state = 0;

    unwind_protect::run_frame (uwp_frame);

    return retval;
  }

We might need to do similar things in other places in the Octave
sources.  It seems undesirable to duplicate this code in many places,
especially if the details of exception handling at the scripting
language level changes in the future, because then we would have to
modify this in many places.

Maybe we should have

  #define OCTAVE_TRY(FRAME_ID) \
    unwind_protect::frame_id_t FRAME_ID = unwind_protect::begin_frame (); \
   \
    unwind_protect::protect_var (buffer_error_messages); \
    unwind_protect::protect_var (Vdebug_on_error); \
    unwind_protect::protect_var (Vdebug_on_warning); \
   \
    buffer_error_messages++; \
    Vdebug_on_error = false; \
    Vdebug_on_warning = false;

  #define OCTAVE_CATCH \
     error_state = 0;

  #define OCTAVE_TRY_CATCH_END(FRAWE_ID) \
    unwind_protect::run_frame (FRAME_ID)

then we could write

  OCTAVE_TRY (uwp_frame)
    some_code...
  OCTAVE_CATCH
    some_cleanup_code...
  OCTAVE_TRY_CATCH_END (uwp_frame)

and if the details change, we would only have to modify the
definitions of the macros.

It seems a little messy to have to specify the frame ID in both the
TRY and TRY_CATCH_END macros.

Also, you must use the OCTAVE_CATCH macro even if you don't have
cleanup code (setting error_state to 0 in the OCTAVE_TRY_CATCH_END
macro would cause trouble if the cleanup code happened to throw an
error.

Hmm.  Is there a better way?  Comments?

jwe


reply via email to

[Prev in Thread] Current Thread [Next in Thread]