Example exception handler; prints a warning to stderr.

    tries_remaining: The number of tries remaining.
    exception: The exception instance which was raised.
766646
def example_exc_handler(tries_remaining, exception, delay):
    

    print >> stderr, "Caught '{0}', {1} tries remaining, \
    sleeping for {2} seconds".format(exception, tries_remaining, delay)
1101321
def _log_unhandled_exception_and_exit(cls, exc_class=None, exc=None, tb=None, add_newline=False):
    """"""
    exc_class = exc_class or sys.exc_info()[0]
    exc = exc or sys.exc_info()[1]
    tb = tb or sys.exc_info()[2]

    # This exception was raised by a signal handler with the intent to exit the program.
    if exc_class == SignalHandler.SignalHandledNonLocalExit:
      return cls._handle_signal_gracefully(exc.signum, exc.signame, exc.traceback_lines)

    extra_err_msg = None
    try:
      # Always output the unhandled exception details into a log file, including the traceback.
      exception_log_entry = cls._format_unhandled_exception_log(exc, tb, add_newline,
                                                                should_print_backtrace=True)
      cls.log_exception(exception_log_entry)
    except Exception as e:
      extra_err_msg = 'Additional error logging unhandled exception {}: {}'.format(exc, e)
      logger.error(extra_err_msg)

    # Generate an unhandled exception report fit to be printed to the terminal (respecting the
    # Exiter's should_print_backtrace field).
    stderr_printed_error = cls._format_unhandled_exception_log(
      exc, tb, add_newline,
      should_print_backtrace=cls._should_print_backtrace_to_terminal)
    if extra_err_msg:
      stderr_printed_error = '{}\n{}'.format(stderr_printed_error, extra_err_msg)
    cls._exit_with_failure(stderr_printed_error)
1193618
def print_err(self, *lst):
      
      self.print2file(self.stderr, False, True, *lst)
210001
def errno_from_exception(self, ex):
        
        if hasattr(ex, 'errno'):
            return ex.errno
        elif ex.args:
            return ex.args[0]
        else:
            return None
246989
def catch_error(exception)
      if handler = handler_for_error(exception)
        handler.arity.zero? ? handler.call : handler.call(exception)
        true
      end
    end
366284
def stderr(self):
        
        stream = self._log_file_handle if self._log_file_handle else osutils.stderr()
        return StreamWriter(stream, self._is_debugging)
908180
def exception_catcher(fn):
    
    exceptions = Queue.Queue()

    @wraps(fn)
    def wrapped(*args, **kwargs):
        try:
            ret = fn(*args, **kwargs)
        except Exception:
            exceptions.put(sys.exc_info())
            raise
        return ret

    def check():
        try:
            item = exceptions.get(block=False)
            klass, value, tb = item
            raise klass, value, tb
        except Queue.Empty:
            pass

    setattr(wrapped, 'check', check)
    return wrapped
980810
def _on_process_stderr_ready(self):
        
        try:
            o = self.readAllStandardError()
        except (TypeError, RuntimeError):
            # widget already deleted
            return
        try:
            output = bytes(o).decode(self._encoding)
        except TypeError:
            output = bytes(o.data()).decode(self._encoding)
        for line in output.splitlines():
            self._srv_logger.error(line)
1278310
async def handle_exception(self, error: Exception) -> Response:
        
        await got_request_exception.send(self, exception=error)

        self.log_exception(sys.exc_info())

        if self.propagate_exceptions:
            return await traceback_response()

        internal_server_error = all_http_exceptions[500]()
        handler = self._find_exception_handler(internal_server_error)

        if handler is None:
            return internal_server_error.get_response()
        else:
            return await self.finalize_request(await handler(error), from_error_handler=True)
90569
def _exception(etype, eval_, etrace):
        
        if hasattr(sys, 'ps1') or not sys.stderr.isatty():
            # we are in interactive mode or we don't have a tty-like
            # device, so we call the default hook
            sys.__excepthook__(etype, eval_, etrace)
        else:
            # we are NOT in interactive mode, print the exception...
            traceback.print_exception(etype, eval_, etrace, limit=2,
                                      file=sys.stdout)
            six.print_()
            # ...then start the debugger in post-mortem mode.
            pdb.pm()
447597
def exception_handler(self, ex):  # pylint: disable=no-self-use
        
        if isinstance(ex, CLIError):
            logger.error(ex)
        else:
            logger.exception(ex)
        return 1
663157
def _exception_raise(self):
        
        exc = self.exc_info()[:]
        try:
            exc_type, exc_value, exc_traceback = exc
        except ValueError:
            exc_type, exc_value = exc
            exc_traceback = None

        # raise exc_type(exc_value).with_traceback(exc_traceback)
        if sys.version_info[0] == 2:
            exec("raise exc_type, exc_value, exc_traceback")
        else: #  sys.version_info[0] == 3:
            if isinstance(exc_value, Exception): #hasattr(exc_value, 'with_traceback'):
                # If exc_value is an exception, then just reraise
                exec("raise exc_value.with_traceback(exc_traceback)")
            else:
                # else we'll create an exception using the value and raise that
                exec("raise exc_type(exc_value).with_traceback(exc_traceback)")
827928
def raiseError(cls, message):
        
        error_message = "[error] %s" % message
        if cls.__raise_exception__:
            raise Exception(error_message)

        cls.colorprint(error_message, Fore.RED)
        sys.exit(1)
465245
def get_exception(self):
        
        exception = known_errors.get(self.code)
        if exception:
            return exception(self)
        else:
            return self
902764
def exception(self, *exceptions):
        

        def response(handler):
            for exception in exceptions:
                if isinstance(exception, (tuple, list)):
                    for e in exception:
                        self.error_handler.add(e, handler)
                else:
                    self.error_handler.add(exception, handler)
            return handler

        return response
63552
def print_exception(exception, secret_values=None):
    
    print(brief_exception_text(exception, secret_values), file=sys.stderr)
1253434
def raise_failure_exception(self, expect_or_allow='Allowed'):
        

        raise MockExpectationError(
            "{} '{}' to be called {}on {!r} with {}, but was not. ({}:{})".format(
                expect_or_allow,
                self._method_name,
                self._call_counter.error_string(),
                self._target.obj,
                self._expected_argument_string(),
                self._caller.filename,
                self._caller.lineno,
            )
        )