Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: return exception from function

suppose I have the following function:

def test():
  ...
  if x['error']:
    raise

This would raise an exception regardless if x['error'] is defined or not.

Instead if I try this, it doesn't throw any exception:

def test():
  ...
  try:
    if x['error']:
      raise
  except:
    return

How can I test for a specific value and return an exception if it is defined, and to return successfully if it is not defined?

like image 201
Subbeh Avatar asked Sep 04 '18 02:09

Subbeh


People also ask

Can we return an exception from a function in Python?

Use raise to throw exceptions in Python If you have a specific condition in your function that should loudly crash your program (if/when that condition is met) you can raise an exception by using the raise statement and providing an exception object to raise.

How do I return an exception error in Python?

As a Python developer you can choose to throw an exception if a condition occurs. To throw (or raise) an exception, use the raise keyword.

How do you capture an exception in Python?

Catching Exceptions in Python In Python, exceptions can be handled using a try statement. The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause.

Does raise in Python return?

You can't raise and return , but you could return multiple values, where the first is the same as what you're currently using, and the second indicates if an exception arose return True, sys.


1 Answers

If you want to return error as string:

>>> def test():
    try:
        if x['error']:raise
    except Exception as err:
        return err

>>> test()
NameError("name 'x' is not defined",)

If you want to an error to occur:

>>> def test():
    try:
        if x['error']:raise
    except:
        raise

>>> test()
Traceback (most recent call last):
  File "<pyshell#20>", line 1, in <module>
    test()
  File "<pyshell#19>", line 3, in test
    if x['error']:raise
NameError: name 'x' is not defined
like image 189
Black Thunder Avatar answered Oct 12 '22 06:10

Black Thunder