{"id":222,"hash":"5915fee9e8469e12ae667233e415eaf76ac81a8442737ff6831450ce1a6cf606","pattern":"Manually raising (throwing) an exception in Python","full_message":"How do I raise an exception in Python so that it can later be caught via an except block?","ecosystem":"pypi","package_name":"exception","package_version":null,"solution":"How do I manually throw/raise an exception in Python?\n\nUse the most specific Exception constructor that semantically fits your issue.\n\nBe specific in your message, e.g.:\n\nraise ValueError('A very specific bad thing happened.')\n\nDon't raise generic exceptions\nAvoid raising a generic Exception. To catch it, you'll have to catch all other more specific exceptions that subclass it.\n\nProblem 1: Hiding bugs\nraise Exception('I know Python!') # Don't! If you catch, likely to hide bugs.\n\nFor example:\n\ndef demo_bad_catch():\n    try:\n        raise ValueError('Represents a hidden bug, do not catch this')\n        raise Exception('This is the exception you expect to handle')\n    except Exception as error:\n        print('Caught this error: ' + repr(error))\n\n>>> demo_bad_catch()\nCaught this error: ValueError('Represents a hidden bug, do not catch this',)\n\nProblem 2: Won't catch\nAnd more specific catches won't catch the general exception:\n\ndef demo_no_catch():\n    try:\n        raise Exception('general exceptions not caught by specific handling')\n    except ValueError as e:\n        print('we will not catch exception: Exception')\n \n\n>>> demo_no_catch()\nTraceback (most recent call last):\n  File \"<stdin>\", line 1, in <module>\n  File \"<stdin>\", line 3, in demo_no_catch\nException: general exceptions not caught by specific handling\n\nBest Practices: raise statement\nInstead, use the most specific Exception constructor that semantically fits your issue.\n\nraise ValueError('A very specific bad thing happened')\n\nwhich also handily allows an arbitrary number of arguments to be passed to the constructor:\n\nraise ValueError('A very specific bad thing happened', 'foo', 'bar', 'baz') \n\nThese arguments are accessed by the args attribute on the Exception object. For example:\n\ntry:\n    some_code_that_may_raise_our_value_error()\nexcept ValueError as err:\n    print(err.args)\n\nprints\n\n('message', 'foo', 'bar', 'baz')    \n\nIn 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.\n\nBest Practices: except clause\nWhen 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:\n\nlogger = logging.getLogger(__name__)\n\ntry:\n    do_something_in_app_that_breaks_easily()\nexcept AppError as error:\n    logger.error(error)\n    raise                 # just this!\n    # raise AppError      # Don't do this, you'll lose the stack trace!\n\nDon't modify your errors... but if you insist.\nYou 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.\n\nTo explain - the sys.exc_info() returns the type, value, and traceback.\n\ntype, value, traceback = sys.exc_info()\n\nThis is the syntax in Python 2 - note this is not compatible with Python 3:\n\nraise AppError, error, sys.exc_info()[2] # avoid this.\n# Equivalently, as error *is* the second object:\nraise sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]\n\nIf you want to, you can modify what happens with your new raise - e.g. setting new args for the instance:\n\ndef error():\n    raise ValueError('oops!')\n\ndef catch_error_modify_message():\n    try:\n        error()\n    except ValueError:\n        error_type, error_instance, traceback = sys.exc_info()\n        error_instance.args = (error_instance.args[0] + ' <modification>',)\n        raise error_type, error_instance, traceback\n\nAnd 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).\n\n>>> catch_error_modify_message()\nTraceback (most recent call last):\n  File \"<stdin>\", line 1, in <module>\n  File \"<stdin>\", line 3, in catch_error_modify_message\n  File \"<stdin>\", line 2, in error\nValueError: oops! <modification>\n\nIn Python 3:\n\nraise error.with_traceback(sys.exc_info()[2])\n\nAgain: 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.)\n\nPython 3, Exception chaining\nIn Python 3, you can chain Exceptions, which preserve tracebacks:\n\nraise RuntimeError('specific message') from error\n\nBe aware:\n\nthis does allow changing the error type raised, and\nthis is not compatible with Python 2.\n\nDeprecated Methods:\nThese 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!\n\nValid in Python 2, but not in Python 3 is the following:\n\nraise ValueError, 'message' # Don't do this, it's deprecated!\n\nOnly valid in much older versions of Python (2.4 and lower), you may still see people raising strings:\n\nraise 'message' # really really wrong. don't do this.\n\nIn 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.\n\nExample Usage\nI raise Exceptions to warn consumers of my API if they're using it incorrectly:\n\ndef api_func(foo):\n    '''foo should be either 'baz' or 'bar'. returns something very useful.'''\n    if foo not in _ALLOWED_ARGS:\n        raise ValueError('{foo} wrong, use \"baz\" or \"bar\"'.format(foo=repr(foo)))\n\nCreate your own error types when apropos\n\n\"I want to make an error on purpose, so that it would go into the except\"\n\nYou 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:\n\nclass MyAppLookupError(LookupError):\n    '''raise this when there's a lookup error for my app'''\n\nand usage:\n\nif important_key not in resource_dict and not ok_to_be_missing:\n    raise MyAppLookupError('resource is missing, and that is not ok.')","confidence":0.95,"source":"stackoverflow","source_url":"https://stackoverflow.com/questions/2052390/manually-raising-throwing-an-exception-in-python","votes":3320,"created_at":"2026-04-19T04:41:34.550388+00:00","updated_at":"2026-04-19T04:51:46.373511+00:00"}