🌐
Python documentation
docs.python.org › 3 › tutorial › errors.html
8. Errors and Exceptions — Python 3.14.3 documentation
The sole argument to raise indicates the exception to be raised. This must be either an exception instance or an exception class (a class that derives from BaseException, such as Exception or one of its subclasses).
🌐
W3Schools
w3schools.com › python › ref_keyword_raise.asp
Python raise Keyword
Python Examples Python Compiler ... Interview Q&A Python Bootcamp Python Certificate Python Training ... The raise keyword is used to raise an exception....
🌐
W3Schools
w3schools.com › python › gloss_python_raise.asp
Python Raise an Exception
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.
🌐
Reddit
reddit.com › r/learnpython › explain the term “raise an exception” without using the terms “raise” or “throw”
r/learnpython on Reddit: Explain the term “raise an exception” without using the terms “raise” or “throw”
February 23, 2022 -

I’m a python learner and am pretty ok with the syntax, and am now finding myself struggling with some of the deeper concepts, in this case error handling. Our environment is python running in a pytest framework using some pre-structured functions along with scripts and functions we write ourselves. I have visibility into the scripts and functions I write, along with some of the pre-structured functions, but the lowest level functions are beyond my view and control. I regularly run into exceptions in these lower levels and am trying to understand what’s going on. All the references I find say something like “raising an exception is when an executions error occurs, the error is raised as an exception”. This makes me nuts as they are explaining the term by using the term. So… Q1: what happens when an “exception is raised”? In terms of program execution and control and variables. Q2: if my script calls a function1 that calls a function2 which contains a command that “raises an exception” can I catch and handle it in function1 or in my top-level script, and if so, how? Q3: if I’m asking the wrong question, what should I be asking and/or researching?

Top answer
1 of 5
4
Try reading about excepting handling in python with some example code, this should help you understand. https://www.programiz.com/python-programming/exception-handling TL;DR; sequential execution is stopped when an exception happens, and it looks for an except: block to handle it, and starts executing a matching except block. If no such block found anywhere, including above functions etc, it is finally shown as an error to the user stopping the entire code.
2 of 5
4
So… Q1: what happens when an “exception is raised”? Go back a step - what happens when a function is called? Maybe you've got an idea, but let's be explicit - what happens is that the interpreter "puts a pin" in what it's currently doing, the line it's currently executing, and it jumps to the body of the function and executes that. Only it's not actually a pin, it's a stack frame. It puts a frame on the call stack - a collection of these frames, in the form of a stack, that the interpreter is using to keep track of where it needs to go back to when the function returns - and starts executing the body of the function that was called. If that function calls a function, then another frame goes on the call stack and you jump into the body of the new function. When the function returns, you "pop" a frame off the stack, and you return to where the function was called, possibly holding a return value. If you've written functions that call functions (that call functions, etc...) then you've had some intuitive notion of "returning" all the way back to where you started. That's called "unwinding the stack." When you raise an exception, somewhere deep in a nest of called functions, what the interpreter does is start removing stack frames from the stack, immediately returning functions wherever they're currently at in their execution. It keeps track as it does so, and you see that in the error output as something called the exception stacktrace: Traceback (most recent call last): File "/path/to/example.py", line 4, in greet('Chad') File "/path/to/example.py", line 2, in greet print('Hello, ' + someon) NameError: name 'someon' is not defined The interpreter pops stack frames until one of two things happens - either you pop all the way to an empty stack and your Python program exits with a relevant error code, or you pop into the body of a try block. If the try block is followed by an except block that declares it can handle errors of that type (so, except NameError to catch our example exception above) then the interpreter stops popping stack frames and moves execution to that except block and continues from there. That's what it means to raise an exception - it means "start to unwind the execution call stack of your program until the interpreter finds itself in a frame where the exception can be handled, or it runs out of frames."
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-raise-keyword
Python Raise Keyword - GeeksforGeeks
July 23, 2025 - Python raise Keyword is used to raise exceptions or errors. The raise keyword raises an error and stops the control flow of the program.
🌐
Reddit
reddit.com › r/learnpython › eli5: what is the purpose of raising exceptions?
r/learnpython on Reddit: ELI5: What is the purpose of raising exceptions?
December 16, 2017 -

Bit of background: I used to do some programming when I was in middle school and high school, with basic, visual basic, and c++. But then I went to college and ended up stopping. So, I haven't really done any coding in like 15 to 20 years. I ended up looking for a program that apparently doesn't exists, so recently, I decided to retake up coding to make it for myself. So I started using SoloLearn, and I just learned about handling and raising exceptions.

I can see the purpose behind exception handling, but I can't see how "raise" would be useful. Could anyone enlighten me as to why you would raise an exception?

Top answer
1 of 5
25
Exceptions are raised when an exceptional situation occurs, eg something the program doesn't want to happen. In case the programmer itself determines a situation to be 'exceptional', eg incorrect user input, unexpected calculation result, basically anything out of the ordinary it can raise an exception to stop the flow. The big difference between just 'checking' if it's ok, like doing def divide(dividend, divisor): if divisor == 0: print('division by zero undefined!') return # what should it return??? return dividend / divisor Because when the caller doesn't check the return value, it doesn't detect the None being returned (or whatever you choose to return) # this will just store None in the dict as if it's somehow 'ok' my_dict[result] = divide(1/0) Instead you would like to have the function raise an exception to notify the user that it's actually breaking if divisor == 0: raise ValueError('division by zero not undefined!') As then the store in my_dict will not happen as the exception occurs before it being saved. Of course Python has a built-in ZeroDivisionError for this, but you get the idea why stuff like this should raise exceptions and not 'work' until you do sum_of_all_values = sum(my_dict.values()) which raises an exception because the None value stored can't be part of a sum. So it shouldn't matter if it's Python or the programmer who raises the exception, what matters is that they are raised when something happens that shouldn't keep 'working'.
2 of 5
4
There's a lot of reasons you may want to raise an exception. Usually this would be because you know some fatal or unexpected bad thing may happen if you don't. You may also raise an exception with a specific message to provide better information to a user. This is particularly important when designing interfaces that other people will use. In many other languages, 'look before you leap' is a philosophy for dealing with potentially error-prone operations. In Python 'easier to ask forgiveness than permission' is more often used than in some other languages. Exceptions are what make that philosophy work well. Many libraries even make their own exception classes to raise in particular cases to be more informative. This aides users in exception handling and understanding why exceptions happen. Also consider that, at some level, you are able to handle exceptions because somebody before you decided to raise an exception.
🌐
Real Python
realpython.com › ref › keywords › raise
raise | Python Keywords – Real Python
In Python, the raise keyword allows you to trigger exceptions manually.
🌐
Python.org
discuss.python.org › ideas
`raise` as a function - Ideas - Discussions on Python.org
October 17, 2025 - In Python,raise is a keyword (used to raise exceptions). Recently I was writing some code that was using ‘boolean-operations’, like: x = a() or b() Resulting in x getting the value of b() if a() returned falsy. But b…
Find elsewhere
🌐
Python Morsels
pythonmorsels.com › how-to-throw-an-exception
How to raise an exception in Python - Python Morsels
January 17, 2022 - 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 (a.k.a. "throw an exception") by using the raise statement and providing an exception object to raise. You can make an exception object by calling an exception class, passing in a helpful error message. ... Python Jumpstart is designed to help new Python programmers get up to speed quickly.
🌐
Python
docs.python.org › 3 › library › exceptions.html
Built-in Exceptions — Python 3.14.3 documentation
Raised when the interpreter finds an internal error, but the situation does not look so serious to cause it to abandon all hope. The associated value is a string indicating what went wrong (in low-level terms). In CPython, this could be raised by incorrectly using Python’s C API, such as returning a NULL value without an exception set.
Top answer
1 of 4
6

The answer to your question is you want meaningful exceptions.

In most contexts, this involves an exception that adds actionable information in one of two ways:

  • Useful typing to the developer who might be catching the exception
  • Useful error information to the user (and/or to the developer who can translate to that the user)

In your example, you aren't really adding anything to the normal exception. Catching and then effectively reraising the exception isn't useful. You could log this information, in which case you now added some value to the exception, but otherwise it's pointless.

Imagine this scenario:

try:
   my_web_function()
except my_custom_web_exception:
   do_something_with_this_exception()

It's entirely reasonable to imagine this scenario. You might make an http request. Most libraries have defined exception types, so you could catch those exceptions, and if it happens, do something.

The "something" is dependent on the specific application. In a http exception, maybe it's just retry the request. Etc.

But the point is catching the exception adds value and information and is actionable.

2 of 4
3

An error I encountered late last week wasn't due to a python script, but the same principle applies. I had the "privilege" of having to use an old version of subversion on a project. I mistakenly mistyped

prompt: svn co https://some.site.com/some/path

The system's response was

svn: OPTIONS of 'https://some.site.com/some/path': 200 OK (https://some.site.com)

This message was not only unhelpful, it was incorrect. (Giving someone an HTTP/HTTPS "200 OK" status when what happened was far from okay is not OK.) Moreover, there are multiple pathways in subversion 1.9 that result in that erroneous "200 OK" error message. A much more helpful message would have been to tell me that I had mistyped the repository's URL.

Strictly speaking, this was not a bug in subversion. It was just a poorly worded error message. After all, subversion did properly detect and report the problem. From a user perspective, this was a huge bug that was mostly fixed in 2010. Thankfully, a quick google search resulted in multiple hits at stackoverflow.com.


Programmers are often taught that they should simply let an exception pass through if they can't do something about it. Instructors as well as students think "doing something" means correcting the problem. In many cases, there is nothing that can be done to correct a problem. This is an overly narrow view of "doing something." Adding context that enables a user to hone in on the problem and then fix it is "doing something."

Another way of looking at letting low level exceptions bubble up is that doing so is a leaky abstraction.

🌐
Sentry
sentry.io › sentry answers › python › raise an exception in python
Raise an exception in Python | Sentry
June 15, 2023 - Python provides a large number of default exceptions arranged in a class hierarchy from least to most specific. When catching exceptions, all subclasses will be caught by except clauses using their parents. Therefore, the topmost class Exception is likely to be missed in favor of an exception that uses one of its subclasses. Consider the code below: def divide_by_zero(): return 1 / 0 # will fail and raise a ZeroDivisionError try: divide_by_zero() raise Exception("My custom exception.") except Exception as e: print(f"Caught error: {repr(e)}")
🌐
Python.org
discuss.python.org › documentation
Raise vs throw in docs - Documentation - Discussions on Python.org
November 17, 2022 - Terminology: are the terms “raise” and “throw” when talking about exceptions in the docs considered entirely equivalent? Obviously, one is a language keyword and the other is not. A little muddled in that generators have a throw method, but disregarding that… is this anything to care ...
🌐
Coursera
coursera.org › tutorials › python-exception
How to Catch, Raise, and Print a Python Exception | Coursera
Additionally, handling exceptions this way enables you to replace the interpreter’s error message with a much more user friendly one. The raise statement allows you to force an error to occur.
Top answer
1 of 6
18

Returning and raising are mutually exclusive.

Raising SystemExit will end the script. A few cleanup routines get to run, and if the caller really, really wants to, they can catch the SystemExit and cancel it, but mostly, you can think of it as stopping execution right there. The caller will never get a chance to see a return value or do anything meaningful with it.

Returning means you want the script to continue. Continuing might mean having the caller raise SystemExit, or it might mean ignoring the error, or it might mean something else. Whatever it means is up to you, as you're the one writing the code.

Finally, are you sure you should be handling this error at all? Catching an exception only to turn it into a system shutdown may not be the most useful behavior. It's not a user-friendly way to deal with problems, and it hides all the useful debugging information you'd get from a stack trace.

2 of 6
5

You can raise an error with a 'returning_value' argument to be used after the calling.

Another pythonic answer to your problem could be to make use of the error arguments in the raise and then, in your call manage the error to get the value, convert it from string and get your 'return-ish'.

def your_f():
    try:
      some_io_thingy_ok()
      return 1
    except IOError:
        raise SystemExit("FOOBAR", 0)

try:
    my_returning_value = your_f()
except SystemExit as err:
    my_returning_value = err.args[1]


print(my_returning_value)

From Python 3 docs :

When an exception occurs, it may have an associated value, also known as the exception’s argument. The presence and type of the argument depend on the exception type.

The except clause may specify a variable after the exception name. The variable is bound to an exception instance with the arguments stored in instance.args. For convenience, the exception instance defines str() so the arguments can be printed directly without having to reference .args. One may also instantiate an exception first before raising it and add any attributes to it as desired.

🌐
Python
peps.python.org › pep-3109
PEP 3109 – Raising Exceptions in Python 3000 | peps.python.org
Because of its relation to exception raising, the signature for the throw() method on generator objects will change, dropping the optional second and third parameters. The signature thus changes (PEP 342) from ... Where EXCEPTION is either a subclass of BaseException or an instance of a subclass of BaseException. In Python 2, the following raise statement is legal
🌐
Python documentation
docs.python.org › 3 › reference › simple_stmts.html
7. Simple statements — Python 3.14.3 documentation
Raises an auditing event import with arguments module, filename, sys.path, sys.meta_path, sys.path_hooks. A future statement is a directive to the compiler that a particular module should be compiled using syntax or semantics that will be available ...
🌐
Real Python
realpython.com › python-raise-exception
Python's raise: Effectively Raising Exceptions in Your Code – Real Python
January 25, 2025 - In this tutorial, you'll learn how to raise exceptions in Python, which will improve your ability to efficiently handle errors and exceptional situations in your code. This way, you'll write more reliable, robust, and maintainable code.