Consumes the given PyResult to raise/return the exception/value it represents.
555838
def raise_or_return(self, pyresult):
    """"""
    value = self.from_value(pyresult.handle)
    self._handles.remove(pyresult.handle)
    if pyresult.is_throw:
      raise value
    else:
      return value
877707
def schedule_exception(exception, target):
    
    if not isinstance(target, compat.greenlet):
        raise TypeError("can only schedule exceptions for greenlets")
    if target.dead:
        raise ValueError("can't send exceptions to a dead greenlet")
    schedule(target)
    state.to_raise[target] = exception
995814
def catch_raise_api_exception():
    """"""
    try:
        yield
    except _ApiException as exc:
        detail = None
        fields = None

        if exc.body:
            try:
                # pylint: disable=no-member
                data = json.loads(exc.body)
                detail = data.get("detail", None)
                fields = data.get("fields", None)
            except ValueError:
                pass

        detail = detail or exc.reason

        raise ApiException(
            exc.status, detail=detail, headers=exc.headers, body=exc.body, fields=fields
        )
792350
def _from_exception(cls, pe):
        
        return cls(pe.pstr, pe.loc, pe.msg, pe.parserElement)
1235593
private <T> T execute(UriComponentsBuilder uriTemplate, HttpMethod method,
			MultiValueMap<String, String> requestData, Class<T> responseType) throws EtcdException {
		long startTimeMillis = System.currentTimeMillis();
		int retry = -1;

		ResourceAccessException lastException = null;
		do {
			lastException = null;

			URI uri = uriTemplate.buildAndExpand(locations[locationIndex]).toUri();

			RequestEntity<MultiValueMap<String, String>> requestEntity = new RequestEntity<>(requestData, null, method,
					uri);

			try {
				ResponseEntity<T> responseEntity = template.exchange(requestEntity, responseType);
				return responseEntity.getBody();
			} catch (HttpStatusCodeException e) {
				EtcdError error = null;
				try {
					error = responseConverter.getObjectMapper().readValue(e.getResponseBodyAsByteArray(),
							EtcdError.class);
				} catch (IOException ex) {
					error = null;
				}
				throw new EtcdException(error, "Failed to execute " + requestEntity + ".", e);
			} catch (ResourceAccessException e) {
				log.debug("Failed to execute " + requestEntity + ", retrying if possible.", e);

				if (locationIndex == locations.length - 1) {
					locationIndex = 0;
				} else {
					locationIndex++;
				}
				lastException = e;
			}
		} while (retry <= retryCount && System.currentTimeMillis() - startTimeMillis < retryDuration);

		if (lastException != null) {
			throw lastException;
		} else {
			return null;
		}
	}
1153671
def _maybe_wrap_exception(exception):
    """"""
    if isinstance(exception, grpc.RpcError):
        return exceptions.from_grpc_error(exception)
    return exception
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,
            )
        )
1136482
def throws(exc):
    '''
    
    '''
    if not __CHECKING__:
        return lambda f: f

    def wrap(f):
        def call(*args, **kwd):
            res = f(*args, **kwd)
            # raise UncheckedExceptionError if exc is not automatically
            # registered by a function decorated with @catches(exc);
            # otherwise do nothing
            exc_checker.throwing(exc)
            return res
        call.__name__ = f.__name__
        return call
    return wrap
535082
def match(match_expr, exc_type, exc_value, exc_traceback):
    
    # Emulate standard behavior when match_expr is an exception subclass.
    if isinstance(match_expr, type) and issubclass(match_expr, BaseException):
        return issubclass(exc_type, match_expr)

    # Match on type and args when match_expr is an exception instance.
    return (
        issubclass(exc_type, type(match_expr))
        and
        match_expr.args == exc_value.args
    )
332989
private Object invokeRpc(Method method, Object[] args) throws Exception {
		String methodName = method.getName();
		Class<?>[] parameterTypes = method.getParameterTypes();
		Annotation[][] parameterAnnotations = method.getParameterAnnotations();
		Time futureTimeout = extractRpcTimeout(parameterAnnotations, args, timeout);

		final RpcInvocation rpcInvocation = createRpcInvocationMessage(methodName, parameterTypes, args);

		Class<?> returnType = method.getReturnType();

		final Object result;

		if (Objects.equals(returnType, Void.TYPE)) {
			tell(rpcInvocation);

			result = null;
		} else {
			// execute an asynchronous call
			CompletableFuture<?> resultFuture = ask(rpcInvocation, futureTimeout);

			CompletableFuture<?> completableFuture = resultFuture.thenApply((Object o) -> {
				if (o instanceof SerializedValue) {
					try {
						return  ((SerializedValue<?>) o).deserializeValue(getClass().getClassLoader());
					} catch (IOException | ClassNotFoundException e) {
						throw new CompletionException(
							new RpcException("Could not deserialize the serialized payload of RPC method : "
								+ methodName, e));
					}
				} else {
					return o;
				}
			});

			if (Objects.equals(returnType, CompletableFuture.class)) {
				result = completableFuture;
			} else {
				try {
					result = completableFuture.get(futureTimeout.getSize(), futureTimeout.getUnit());
				} catch (ExecutionException ee) {
					throw new RpcException("Failure while obtaining synchronous RPC result.", ExceptionUtils.stripExecutionException(ee));
				}
			}
		}

		return result;
	}
1079327
def raise_invalid_type_exception(self):
        """"""
        message = 'Expecting element type of %s' % (
            self._parameter.element_type.__name__)
        err = ValueError(message)
        return err
921143
protected void consumeUntilGreedy(Parser recognizer, IntervalSet set, CSSLexerState.RecoveryMode mode) {
        CSSToken t;
        do {
            Token next = recognizer.getInputStream().LT(1);
            if (next instanceof CSSToken) {
                t = (CSSToken) recognizer.getInputStream().LT(1);
                if (t.getType() == Token.EOF) {
                    logger.trace("token eof ");
                    break;
                }
            } else
                break; /* not a CSSToken, probably EOF */
            logger.trace("Skipped greedy: {}", t.getText());
            // consume token even if it will match
            recognizer.consume();
        }
        while (!(t.getLexerState().isBalanced(mode, null, t) && set.contains(t.getType())));
    }
34863
def _raise_exception(self, eobj, edata=None):
        """"""
        _, _, tbobj = sys.exc_info()
        if edata:
            emsg = self._format_msg(eobj["msg"], edata)
            _rwtb(eobj["type"], emsg, tbobj)
        else:
            _rwtb(eobj["type"], eobj["msg"], tbobj)
929628
def gather(self, futures, consume_exceptions=True):
        

        # from the asyncio docs: "If return_exceptions is True, exceptions
        # in the tasks are treated the same as successful results, and
        # gathered in the result list; otherwise, the first raised
        # exception will be immediately propagated to the returned
        # future."
        return asyncio.gather(*futures, return_exceptions=consume_exceptions)
349487
def raise_api_exceptions(function, *args, **kwargs):
    
    try:
        return_value = function(*args, **kwargs)
    except errors.HTTPException as exc:
        if exc._raw.status_code != 400:  # pylint: disable=W0212
            raise  # Unhandled HTTPErrors
        try:  # Attempt to convert v1 errors into older format (for now)
            data = exc._raw.json()  # pylint: disable=W0212
            assert len(data) == 2
            return_value = {'errors': [(data['reason'],
                                        data['explanation'], '')]}
        except Exception:
            raise exc
    if isinstance(return_value, dict):
        if return_value.get('error') == 304:  # Not modified exception
            raise errors.NotModified(return_value)
        elif return_value.get('errors'):
            error_list = []
            for error_type, msg, value in return_value['errors']:
                if error_type in errors.ERROR_MAPPING:
                    if error_type == 'RATELIMIT':
                        args[0].evict(args[1])
                    error_class = errors.ERROR_MAPPING[error_type]
                else:
                    error_class = errors.APIException
                error_list.append(error_class(error_type, msg, value,
                                              return_value))
            if len(error_list) == 1:
                raise error_list[0]
            else:
                raise errors.ExceptionList(error_list)
    return return_value
1297598
private Object invokeValueOf(Class<?> clazz, String value) throws IllegalAccessException,
        InvocationTargetException {
        try {
            return MethodUtils.invokeExactStaticMethod(clazz, "valueOf", value);
        } catch (NoSuchMethodException e) {
            return null;
        }
    }
1270141
@Nonnull
    protected Throwable getResponseException(Throwable e) {
        // Unwrap execution exceptions.
        if (ExecutionException.class.isAssignableFrom(e.getClass())) {
            return getResponseException(e.getCause());
        }
        return e;
    }