By TIMEX


2010-01-12 21:07:40 8 Comments

How can I raise an exception in Python so that it can later be caught via an except block?

8 comments

@markemus 2018-12-03 16:13:19

Just to note: there are times when you DO want to handle generic exceptions. If you're processing a bunch of files and logging your errors, you might want to catch any error that occurs for a file, log it, and continue processing the rest of the files. In that case, a

try:
    foo() 
except Exception as e:
    print(str(e)) # Print out handled error

block is a good way to do it. You'll still want to raise specific exceptions so you know what they mean, though.

@Abhijeet.py 2020-03-31 08:37:30

You should learn the raise statement of python for that. It should be kept inside the try block. Example -

try:
    raise TypeError            #remove TypeError by any other error if you want
except TypeError:
    print('TypeError raised')

@Aaron Hall 2014-06-05 16:30:58

How do I manually throw/raise an exception in Python?

Use the most specific Exception constructor that semantically fits your issue.

Be specific in your message, e.g.:

raise ValueError('A very specific bad thing happened.')

Don't raise generic exceptions

Avoid raising a generic Exception. To catch it, you'll have to catch all other more specific exceptions that subclass it.

Problem 1: Hiding bugs

raise Exception('I know Python!') # Don't! If you catch, likely to hide bugs.

For example:

def demo_bad_catch():
    try:
        raise ValueError('Represents a hidden bug, do not catch this')
        raise Exception('This is the exception you expect to handle')
    except Exception as error:
        print('Caught this error: ' + repr(error))

>>> demo_bad_catch()
Caught this error: ValueError('Represents a hidden bug, do not catch this',)

Problem 2: Won't catch

And more specific catches won't catch the general exception:

def demo_no_catch():
    try:
        raise Exception('general exceptions not caught by specific handling')
    except ValueError as e:
        print('we will not catch exception: Exception')


>>> demo_no_catch()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in demo_no_catch
Exception: general exceptions not caught by specific handling

Best Practices: raise statement

Instead, use the most specific Exception constructor that semantically fits your issue.

raise ValueError('A very specific bad thing happened')

which also handily allows an arbitrary number of arguments to be passed to the constructor:

raise ValueError('A very specific bad thing happened', 'foo', 'bar', 'baz') 

These arguments are accessed by the args attribute on the Exception object. For example:

try:
    some_code_that_may_raise_our_value_error()
except ValueError as err:
    print(err.args)

prints

('message', 'foo', 'bar', 'baz')    

In Python 2.5, an actual message attribute was added to BaseException in favor of encouraging users to subclass Exceptions and stop using args, but the introduction of message and the original deprecation of args has been retracted.

Best Practices: except clause

When inside an except clause, you might want to, for example, log that a specific type of error happened, and then re-raise. The best way to do this while preserving the stack trace is to use a bare raise statement. For example:

logger = logging.getLogger(__name__)

try:
    do_something_in_app_that_breaks_easily()
except AppError as error:
    logger.error(error)
    raise                 # just this!
    # raise AppError      # Don't do this, you'll lose the stack trace!

Don't modify your errors... but if you insist.

You can preserve the stacktrace (and error value) with sys.exc_info(), but this is way more error prone and has compatibility problems between Python 2 and 3, prefer to use a bare raise to re-raise.

To explain - the sys.exc_info() returns the type, value, and traceback.

type, value, traceback = sys.exc_info()

This is the syntax in Python 2 - note this is not compatible with Python 3:

    raise AppError, error, sys.exc_info()[2] # avoid this.
    # Equivalently, as error *is* the second object:
    raise sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]

If you want to, you can modify what happens with your new raise - e.g. setting new args for the instance:

def error():
    raise ValueError('oops!')

def catch_error_modify_message():
    try:
        error()
    except ValueError:
        error_type, error_instance, traceback = sys.exc_info()
        error_instance.args = (error_instance.args[0] + ' <modification>',)
        raise error_type, error_instance, traceback

And we have preserved the whole traceback while modifying the args. Note that this is not a best practice and it is invalid syntax in Python 3 (making keeping compatibility much harder to work around).

>>> catch_error_modify_message()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in catch_error_modify_message
  File "<stdin>", line 2, in error
ValueError: oops! <modification>

In Python 3:

    raise error.with_traceback(sys.exc_info()[2])

Again: avoid manually manipulating tracebacks. It's less efficient and more error prone. And if you're using threading and sys.exc_info you may even get the wrong traceback (especially if you're using exception handling for control flow - which I'd personally tend to avoid.)

Python 3, Exception chaining

In Python 3, you can chain Exceptions, which preserve tracebacks:

    raise RuntimeError('specific message') from error

Be aware:

  • this does allow changing the error type raised, and
  • this is not compatible with Python 2.

Deprecated Methods:

These can easily hide and even get into production code. You want to raise an exception, and doing them will raise an exception, but not the one intended!

Valid in Python 2, but not in Python 3 is the following:

raise ValueError, 'message' # Don't do this, it's deprecated!

Only valid in much older versions of Python (2.4 and lower), you may still see people raising strings:

raise 'message' # really really wrong. don't do this.

In all modern versions, this will actually raise a TypeError, because you're not raising a BaseException type. If you're not checking for the right exception and don't have a reviewer that's aware of the issue, it could get into production.

Example Usage

I raise Exceptions to warn consumers of my API if they're using it incorrectly:

def api_func(foo):
    '''foo should be either 'baz' or 'bar'. returns something very useful.'''
    if foo not in _ALLOWED_ARGS:
        raise ValueError('{foo} wrong, use "baz" or "bar"'.format(foo=repr(foo)))

Create your own error types when apropos

"I want to make an error on purpose, so that it would go into the except"

You can create your own error types, if you want to indicate something specific is wrong with your application, just subclass the appropriate point in the exception hierarchy:

class MyAppLookupError(LookupError):
    '''raise this when there's a lookup error for my app'''

and usage:

if important_key not in resource_dict and not ok_to_be_missing:
    raise MyAppLookupError('resource is missing, and that is not ok.')

@N Randhawa 2016-11-08 17:54:34

In Python3 there are 4 different syntaxes for rasing exceptions:

1. raise exception 
2. raise exception (args) 
3. raise
4. raise exception (args) from original_exception

1. raise exception vs. 2. raise exception (args)

If you use raise exception (args) to raise an exception then the args will be printed when you print the exception object - as shown in the example below.

  #raise exception (args)
    try:
        raise ValueError("I have raised an Exception")
    except ValueError as exp:
        print ("Error", exp)     # Output -> Error I have raised an Exception 



  #raise execption 
    try:
        raise ValueError
    except ValueError as exp:
        print ("Error", exp)     # Output -> Error 

3.raise

raise statement without any arguments re-raises the last exception. This is useful if you need to perform some actions after catching the exception and then want to re-raise it. But if there was no exception before, raise statement raises TypeError Exception.

def somefunction():
    print("some cleaning")

a=10
b=0 
result=None

try:
    result=a/b
    print(result)

except Exception:            #Output ->
    somefunction()           #some cleaning
    raise                    #Traceback (most recent call last):
                             #File "python", line 8, in <module>
                             #ZeroDivisionError: division by zero

4. raise exception (args) from original_exception

This statement is used to create exception chaining in which an exception that is raised in response to another exception can contain the details of the original exception - as shown in the example below.

class MyCustomException(Exception):
pass

a=10
b=0 
reuslt=None
try:
    try:
        result=a/b

    except ZeroDivisionError as exp:
        print("ZeroDivisionError -- ",exp)
        raise MyCustomException("Zero Division ") from exp

except MyCustomException as exp:
        print("MyException",exp)
        print(exp.__cause__)

Output:

ZeroDivisionError --  division by zero
MyException Zero Division 
division by zero

@Gloweye 2019-06-28 07:15:36

Please note that PEP8 prefers exception(args) over exception (args)

@cg909 2020-04-04 17:06:47

There is also raise exception(args) from None to say that the currently active exception was handled and is no longer of interest. Otherwise if you raise an exception inside an except block and it isn't handled, tracebacks for both exceptions will be shown separated by the message “During handling of the above exception, another exception occurred”

@Rehan Haider 2019-02-27 09:42:59

Another way to throw an exceptions is assert. You can use assert to verify a condition is being fulfilled if not then it will raise AssertionError. For more details have a look here.

def avg(marks):
    assert len(marks) != 0,"List is empty."
    return sum(marks)/len(marks)

mark2 = [55,88,78,90,79]
print("Average of mark2:",avg(mark2))

mark1 = []
print("Average of mark1:",avg(mark1))

@cowbert 2020-09-24 16:47:24

not foolproof since asserts in CPython are ignored when the interpreter is inovked with optimizations (-O) flag; if you want to really control program flow "hey this condition shouldn't happen but abend if it is true", manually raise AssertionError()

@Anant Prakash 2017-03-29 11:59:26

Read the existing answers first, this is just an addendum.

Notice that you can raise exceptions with or without arguments.

Example:

raise SystemExit

exits the program but you might want to know what happened.So you can use this.

raise SystemExit("program exited")

this will print "program exited" to stderr before closing the program.

@burny 2019-10-01 08:28:46

Isn't this against the OOP paradigm? I assume, the first case throws the class reference and the second one an instance of SystemExit. Wouldn't raise SystemExit() be the better choice? Why does the first one even work?

@Evgeni Sergeev 2015-05-19 04:55:14

For the common case where you need to throw an exception in response to some unexpected conditions, and that you never intend to catch, but simply to fail fast to enable you to debug from there if it ever happens — the most logical one seems to be AssertionError:

if 0 < distance <= RADIUS:
    #Do something.
elif RADIUS < distance:
    #Do something.
else:
    raise AssertionError("Unexpected value of 'distance'!", distance)

@Two-Bit Alchemist 2015-09-16 21:33:44

This is a better case for ValueError than AssertionError because there's no problem with an assertion (because none is being made here) -- the problem is with a value. If you really want an AssertionError in this case, write assert distance > 0, 'Distance must be positive'. But you shouldn't error check that way because assertions can be turned off (python -O).

@Evgeni Sergeev 2015-09-17 01:31:00

@Two-BitAlchemist Good point. The idea was lost in simplification, when I wrote the simple example above. In many similar cases it's a condition that isn't associated with a particular value. Rather, the meaning is "control flow should never get here".

@Evgeni Sergeev 2015-09-17 01:31:32

@Two-BitAlchemist Assertions can be turned off, yes, but then you shouldn't use them to error check at all?

@Two-Bit Alchemist 2015-09-17 17:05:47

Well it depends. I wouldn't let that be my only error checking in a program I intended to distribute. On the other hand, I could make a program just for my co-workers and tell them they use it at their own risk if they run it with -O.

@Evgeni Sergeev 2015-09-21 02:36:20

@Two-BitAlchemist For me the role of assertions isn't error-checking per se (which is what testing is for), but they set up fences within the code that certain bugs can't get through. So it becomes easier to track down and isolate the bugs, which will inevitably occur. This is just good habits that take little effort, while testing takes a lot of effort and a lot of time.

@Jonathan Hartley 2015-09-29 13:33:16

"testing takes a lot of effort and a lot of time" - true, but not as much as the time and effort it saves.

@Daerdemandt 2016-09-12 18:05:21

The error could be reproduced if pseudo-const RADIUS is somehow set to negative too.

@Gabriel Hurley 2010-01-12 21:08:45

DON'T DO THIS. Raising a bare Exception is absolutely not the right thing to do; see Aaron Hall's excellent answer instead.

Can't get much more pythonic than this:

raise Exception("I know python!")

See the raise statement docs for python if you'd like more info.

@Dawood ibn Kareem 2015-01-21 22:23:36

No please! This removes the potential to be specific about what you catch. It is ENTIRELY the wrong way to do it. Take a look at Aaron Hall's excellent answer instead of this one. It's times like this I wish I could give more than one downvote per answer.

@Dawood ibn Kareem 2015-02-16 09:38:34

@PeterR It's equally terrible that it has so few downvotes. To ANYBODY reading this answer, DO NOT DO THIS EVER! The correct answer is Aaron Hall's one.

@Charlie Parker 2016-10-22 00:07:29

I think there should be a more detailed explanation on why this is wrong or so bad.

@Dinei 2017-02-24 12:42:13

@CharlieParker There is. It's the first part of Aaron Hall's answer.

@codeforester 2017-10-20 18:45:48

Why can't this answer be flagged for deletion? It has got 93 downvotes already!

@Daniel F. 2018-04-13 07:09:35

@codeforester maybe it's because it's answering the question.

@ctpenrose 2018-10-19 23:50:08

This answer is still here because many experienced developers disagree with use of specialized exception classes. I wish I could downvote comments.

@c z 2019-03-27 10:26:29

Agree with @ctpenrose, subclassing Exception can lead to over-engineered code if there is no intention ever to catch that specific error.

@Gloweye 2019-07-04 10:27:34

@cz, the question might just be a single line, but that line states that it is with the specific purpose of catching it. And there are plenty subclasses of Exception in python's standard library that WILL fit nearly all cases. Use the most fitting. It's always better to give plenty information when you're raising an exception, since it's a potential application shutdown and you will need to debug it. It's hard to get less pythonic than refusing to use the standard library.

@Sławomir Lenart 2019-08-20 09:10:50

could be worse: raise BaseException("I know python!")

@Daisy QL 2020-02-25 18:33:01

I totally agree Aaron Hall's answer. According to Aaron's answer, I don't think this one really follow raising a bare Exception is absolutely not a best practice, and don't get it why this one got so many upvotes.

@jangorecki 2020-09-07 17:57:46

This answer has valid use cases, for example replacing print(msg)+exit(1). It is surprising that someone would want to delete it, just because it doesn't fit his/her/common use case or best practices.

Related Questions

Sponsored Content

21 Answered Questions

[SOLVED] How do I list all files of a directory?

  • 2010-07-08 19:31:22
  • duhhunjonn
  • 4699979 View
  • 3470 Score
  • 21 Answer
  • Tags:   python directory

22 Answered Questions

[SOLVED] What are metaclasses in Python?

62 Answered Questions

[SOLVED] How to call an external command?

39 Answered Questions

[SOLVED] How do I check whether a file exists without exceptions?

44 Answered Questions

26 Answered Questions

[SOLVED] Does Python have a ternary conditional operator?

11 Answered Questions

[SOLVED] Proper way to declare custom exceptions in modern Python?

5 Answered Questions

[SOLVED] Catch multiple exceptions in one line (except block)

27 Answered Questions

[SOLVED] Catch multiple exceptions at once?

Sponsored Content