Capture and process any exceptions from the given block.

 @example
   Raven.capture do
     MyApp.run
   end
166439
def capture(options = {})
      if block_given?
        begin
          yield
        rescue Error
          raise # Don't capture Raven errors
        rescue Exception => e
          capture_type(e, options)
          raise
        end
      else
        install_at_exit_hook(options)
      end
    end
1366802
def _handle_run_exception(self, exc):
        
        self.raise_exception(exc, self._current_tups)

        if self.auto_fail:
            failed = set()
            for key, batch in iteritems(self._batches):
                # Only wipe out batches other than current for exit_on_exception
                if self.exit_on_exception or key == self._current_key:
                    for tup in batch:
                        self.fail(tup)
                        failed.add(tup.id)

            # Fail current batch or tick Tuple if we have one
            for tup in self._current_tups:
                if tup.id not in failed:
                    self.fail(tup)

            # Reset current batch info
            self._batches[self._current_key] = []
            self._current_key = None
886206
def _create_capture_exceptions(capture_decider: Callable[[BaseException], bool]) -> Callable:
        
        def wrapped(*args, **kwargs):
            result = CaptureWrapBuilder._capture_exceptions(*args, **kwargs)
            if result.exception is not None:
                if not capture_decider(result.exception):
                    raise result.exception
            return result

        return wrapped
833115
@Override
    public void run() {
        try {
            handle();
        } catch (Exception e) {
            Throwables.throwIfUnchecked(e);
            throw new RuntimeException(e);
        }
    }
285986
def catch_symbol expected_symbol, &block
      thrown_symbol, thrown_value = nil
      begin
        if expected_symbol
          thrown_value = catch :__ms__nothing_thrown do
            catch expected_symbol do
              block.call
              throw :__ms__nothing_thrown, :__ms__nothing_thrown
            end
          end
          thrown_symbol = expected_symbol unless thrown_value == :__ms__nothing_thrown
        else
          block.call
        end
      rescue => e
        raise(e) unless thrown_symbol = extract_thrown_symbol(e)
      end
      [thrown_symbol, thrown_value]
    end
582623
def _execute_handling(self, *eopatches, **kwargs):
        
        self.private_task_config.start_time = datetime.datetime.now()

        caught_exception = None
        try:
            return_value = self.execute(*eopatches, **kwargs)
        except BaseException as exception:
            caught_exception = exception, sys.exc_info()[2]

        if caught_exception is not None:  # Exception is not raised in except statement to prevent duplicated traceback
            exception, traceback = caught_exception
            raise type(exception)('During execution of task {}: {}'.format(self.__class__.__name__,
                                                                           exception)).with_traceback(traceback)

        self.private_task_config.end_time = datetime.datetime.now()
        return return_value
1125072
private void handleExceptions(Subroutine subroutine, InstructionHandle pei, BasicBlock etb) {
        etb.setExceptionThrower(pei);

        // Remember whether or not a universal exception handler
        // is reachable. If so, then we know that exceptions raised
        // at this instruction cannot propagate out of the method.
        boolean sawUniversalExceptionHandler = false;

        List<CodeExceptionGen> exceptionHandlerList = exceptionHandlerMap.getHandlerList(pei);
        if (exceptionHandlerList != null) {
            for (CodeExceptionGen exceptionHandler : exceptionHandlerList) {
                InstructionHandle handlerStart = exceptionHandler.getHandlerPC();
                subroutine.addEdgeAndExplore(etb, handlerStart, HANDLED_EXCEPTION_EDGE);

                if (Hierarchy.isUniversalExceptionHandler(exceptionHandler.getCatchType())) {
                    sawUniversalExceptionHandler = true;
                }
            }
        }

        // If required, mark this block as throwing an unhandled exception.
        // For now, we assume that if there is no reachable handler that handles
        // ANY exception type, then the exception can be thrown out of the
        // method.
        if (!sawUniversalExceptionHandler) {
            if (DEBUG) {
                System.out.println("Adding unhandled exception edge from " + pei);
            }
            subroutine.setUnhandledExceptionBlock(etb);
        }
    }
343811
def run(&block)
      sync do
        raise Shells::AlreadyRunning if running?
        self.run_flag = true
      end

      begin
        run_hook :on_before_run

        debug 'Connecting...'
        connect

        debug 'Starting output buffering...'
        buffer_output

        debug 'Starting session thread...'
        self.session_thread = Thread.start(self) do |sh|
          begin
            begin
              debug 'Executing setup...'
              sh.instance_eval { setup }
              debug 'Executing block...'
              block.call sh
            ensure
              debug 'Executing teardown...'
              sh.instance_eval { teardown }
            end
          rescue Shells::QuitNow
            # just exit the session.
          rescue =>e
            # if the exception is handled by the hook no further processing is required, otherwise we store the exception
            # to propagate it in the main thread.
            unless sh.run_hook(:on_exception, e) == :break
              sh.sync { sh.instance_eval { self.session_exception = e } }
            end
          end
        end

        # process the input buffer while the thread is alive and the shell is active.
        debug 'Entering IO loop...'
        io_loop do
          if active?
            begin
              if session_thread.status    # not dead
                # process input from the session.
                unless wait_for_output
                  inp = next_input
                  if inp
                    send_data inp
                    self.wait_for_output = (options[:unbuffered_input] == :echo)
                  end
                end

                # continue running the IO loop
                true
              elsif session_exception
                # propagate the exception.
                raise session_exception.class, session_exception.message, session_exception.backtrace
              else
                # the thread has exited, but no exception exists.
                # regardless, the IO loop should now exit.
                false
              end
            rescue IOError
              if ignore_io_error
                # we were (sort of) expecting the IO error, so just tell the IO loop to exit.
                false
              else
                raise
              end
            end
          else
            # the shell session is no longer active, tell the IO loop to exit.
            false
          end
        end
      rescue
        # when an error occurs, try to disconnect, but ignore any further errors.
        begin
          debug 'Disconnecting...'
          disconnect
        rescue
          # ignore
        end
        raise
      else
        # when no error occurs, try to disconnect and propagate any errors (unless we are ignoring IO errors).
        begin
          debug 'Disconnecting...'
          disconnect
        rescue IOError
          raise unless ignore_io_error
        end
      ensure
        # cleanup
        run_hook :on_after_run
        self.run_flag = false
      end

      self
    end
98137
def captureQuery(self, query, params=(), engine=None, **kwargs):
        
        return self.capture(
            'raven.events.Query', query=query, params=params, engine=engine,
            **kwargs)
400947
def respond
      inner_error = nil
      rescue_block = proc do |e|
        (env['rack.exception'] = e && raise) unless filters[:error].any? do |f|
          if !f[:args] || f[:args].empty? || f[:args].any? { |type| e.is_a?(type) }
            instance_exec(e, &f[:proc]) unless check_for_failed_condition(f[:conditions])
          end
        end
      end

      begin
        if config[:strip_trailing_slash] == :redirect && request.path =~ %r{[^/]/+$}
          query_string = request.query_string.empty? ? '' : '?' << request.query_string
          redirect(request.path.chomp('/') + query_string, status: 307, halt: false)
          return response.finish
        end
        pass if config[:auto_pass] && eligable_matches.empty?

        if run_filters(:before)
          catch(:halt) {
            begin
              try_matches
            rescue => inner_error
              rescue_block.call(inner_error)
            end
          }
        end
        run_filters(:after)
      rescue => outer_error
        outer_error == inner_error ? raise : catch(:halt) { rescue_block.call(outer_error) }
      end
      response.finish
    end
530240
public void handleExceptionWithRecordProcess(Exception e, Object w)
      {
        final String mName = "handleExceptionWithRecordProcess";
        if(logger.isLoggable(Level.FINER)) 
          logger.logp(Level.FINE, className, mName, e.getClass().getName() + "; " + this.toString());

        if (!isSkipLimitReached() && excMatcher.isSkippableOrRetryable(e))
        {
          // Skip it.  Log it.  Call the SkipProcessListener.
          ++_skipCount;
          logSkip(e);

          if (_skipProcessListener != null) {
              for (SkipProcessListenerProxy skipProcessListenerProxy : _skipProcessListener) {
                  skipProcessListenerProxy.onSkipProcessItem(w, e);
                }
          }
        }
        else
        {
          // No skip.  Throw it back.
          if(logger.isLoggable(Level.FINER)) 
            logger.logp(Level.FINE, className, mName, "No skip.  Rethrow ", e);
          throw new BatchContainerRuntimeException(e);
        }
      }
414254
public void run() {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.entry(tc, "run");
        }

        try {
            framework.stopChain(chainName, 0L);
        } catch (Exception e) {
            FFDCFilter.processException(e, getClass().getName() + ".run", "68",
                                        this, new Object[] { chainName });
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.exit(tc, "run");
        }
    }
1165952
def run_and_capture(*args, **kwargs)
      ret = _wrap_run((proc { |*a, **k| Host.run_and_capture(*a, **k) }), *args, **kwargs)
      @last_err = ret[:err]
      @last_out = ret[:out]
      ret
    end
825714
def check_end_blocks(frame):
    
    try:
        try:
            module_name = frame.f_globals['__name__']
        except KeyError:
            warnings.warn(
                'Can not get the source of an uknown module. '
                'End-of-block syntax check is skipped.',
                EndSyntaxWarning)
            return
        end

        filename = frame.f_globals.get('__file__', '<unknown>')
        try:
            source = inspect.getsource(sys.modules[module_name])
        except Exception:
            warnings.warn(
                'Can not get the source of module "%s". '
                'End-of-block syntax check is skipped.' % (module_name,),
                EndSyntaxWarning)
            return
        end
    finally:
        del frame
    end

    root = ast.parse(source)
    for node in ast.walk(root):
        bodies = get_compound_bodies(node)
        if not bodies:
            continue
        end

        # FIXME: This is an inaccurate hack to handle if-elif-else.
        if (isinstance(node, ast.If) and
                len(node.orelse) == 1 and
                isinstance(node.orelse[0], ast.If)):
            continue
        end

        # FIXME: This is an inaccurate hack to handle try-except-finally
        # statement which is parsed as ast.TryExcept in ast.TryFinally in
        # Python 2.
        if (PY2 and
                isinstance(node, ast.TryFinally) and
                len(node.body) == 1 and
                isinstance(node.body[0], ast.TryExcept)):
            continue
        end

        for body in bodies:
            skip_next = False
            for i, child in enumerate(body):
                if skip_next:
                    skip_next = False
                elif is_end_node(child):
                    raise SyntaxError(
                        '"end" does not close a block.',
                        [filename, child.lineno, child.col_offset,
                         source.splitlines()[child.lineno - 1] + '\n'])
                elif get_compound_bodies(child):
                    try:
                        ok = is_end_node(body[i + 1])
                    except IndexError:
                        ok = False
                    end
                    if not ok:
                        raise SyntaxError(
                            'This block is not closed with "end".',
                            [filename, child.lineno, child.col_offset,
                             source.splitlines()[child.lineno - 1] + '\n'])
                    end
                    skip_next = True
                end
            end
        end
    end
630926
@Override
    public void visitTryCatchBlock(Label start, Label end, Label handler, String exceptionType) {
        if (enabled && exceptionType != null) {
            handlers.put(handler, Type.getObjectType(exceptionType));
        }
        super.visitTryCatchBlock(start, end, handler, exceptionType);
    }
1051519
def run &block
      begin

        # check if user has passed window coord in config, else root window
        @window = Canis::Window.root_window
        awin = @window
        catch(:close) do
          @form = Form.new @window
          #@form.bind_key(KEY_F1, 'help'){ display_app_help } # NOT REQUIRED NOW 2012-01-7 since form does it
          @form.bind_key([?q,?q], 'quit' ){ throw :close } if $log.debug?

          #@message = Variable.new
          #@message.value = ""
          $status_message ||= Variable.new # remember there are multiple levels of apps
          $status_message.value = ""
          #$error_message.update_command { @message.set_value($error_message.value) }
          if block
            begin
              yield_or_eval &block if block_given? 
              # how the hell does a user trap exception if the loop is hidden from him ? FIXME
              loop
            rescue => ex
              $log.debug( "APP.rb rescue reached ")
              $log.debug( ex) if ex
              $log.debug(ex.backtrace.join("\n")) if ex
            ensure
              close
              # putting it here allows it to be printed on screen, otherwise it was not showing at all.
              if ex
                puts "========== EXCEPTION =========="
                p ex 
                puts "==============================="
                puts(ex.backtrace.join("\n")) 
              end
            end
            nil
          else
            #@close_on_terminate = true
            self
          end #if block
        end # :close
      end
    end
303992
@Override
    public void run() {

        if (this.state != null && this.state.cancel) {
            // we were already cancelled, don't run, but still post completion
            this.state.documentCounter = 0;
            this.state.batchCounter = 0;
            runComplete(null);
            return;
        }
        // reset internal state
        this.state = new State();

        Throwable errorInfo = null;

        try {

            replicate();

        } catch (Throwable e) {
            logger.log(Level.SEVERE,String.format("Batch %s ended with error:", this.state.batchCounter),e);
            errorInfo = e;
        }

        runComplete(errorInfo);
    }