🌐
Python documentation
docs.python.org › 3 › tutorial › errors.html
8. Errors and Exceptions — Python 3.14.7 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 Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A 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.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-raise-keyword
Python Raise Keyword - GeeksforGeeks
May 12, 2026 - DSA Python · Data Science · NumPy · Pandas · Practice · Django · Flask · Last Updated : 12 May, 2026 · The raise keyword raises an exception and immediately stops the normal execution of the program.
🌐
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."
🌐
Coursera
coursera.org › tutorials › how to catch, raise, and print a python exception
How to Catch, Raise, and Print a Python Exception | Coursera
August 13, 2024 - 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.
🌐
Reddit
reddit.com › r/learnpython › what's the point of try/except just to raise the exception?
r/learnpython on Reddit: What's the point of try/except just to raise the exception?
July 25, 2025 -

For context, I'm primarily a database guy but have been using Python a lot lately. I know enough to figure out how to do most things I want to do, but sometimes lack the context of why certain patterns are used/preferred.

Looking through some of the code the software engineers at my organization have written in Python, they make use of try/except blocks frequently and I generally understand why. However, they're often writing except blocks that do nothing but raise the exception. For example:

def main() -> None:  
  try:
    run_etl()
  except Exception as err:
    raise err

Sometimes (not always), I'll at least see logger.error(f"Encountered an exception: {err} before they raise the exception (I have no idea why they're not using logger.exception). Still, since we just let the logging module write to sys.stderr I don't know what we're really gaining.

What is the point of wrapping something in a try/except block when the only thing we're doing is raising the exception? I would understand if we were trying to handle exceptions so the program could continue or if we made use of a finally block to do some sort of post-error cleanup, but we're not. It seems to me like we're just catching the error to raise it, when we could have just let the error get raised directly.

TIA!

Top answer
1 of 20
5
What's the point of try/except just to raise the exception? You are correct. This is pointless, and worse, it obfuscates what the code is doing and makes it harder to maintain. I suspect that what may have happened in some of these places is that it used to do something else in the except block, and that got removed without cleaning up the surrounding code. Another possibility is that some of these are the result of someone blindly copying and pasting code they saw elsewhere. This type of thing happens a lot. Sometimes (not always), I'll at least see logger.error(f"Encountered an exception: {err} before they raise the exception (I have no idea why they're not using logger.exception). Still, since we just let the logging module write to sys.stderr I don't know what we're really gaining. That's pretty common. In production you'd run your code in an environment that captures stderr and stdout, parses them, and then indexes them into a logging system (eg: DataDog or Prometheus). Edit: removed bit about printf debugging, as that isn't what the code in question appears to be doing. (Didn't look closely enough earlier, when I was on my phone.)
2 of 20
5
I will often do this by default until I figure out later how I want to handle specific exception types that can happen as a result of specific situations, because thinking about exception handling can distract me from what I am actually trying to accomplish. It can also help with debugging, because you can put print or log statements in the except section in places you think are relevant and narrow down which one causes the problem. Also, enterprises can have standards that any call that could create an exception should each have its own try except, and you often don't need to do error handling more granularly than the function level, so sometimes you just do this. I think in general it is better practice to have more try excepts than fewer, and I rarely feel it can get excessive
🌐
Real Python
realpython.com › ref › keywords › raise
raise | Python Keywords – Real Python
In Python, the raise keyword allows you to trigger exceptions manually.
Find elsewhere
🌐
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…
🌐
YouTube
youtube.com › watch
raise Exception in Python | Python for AI #71 - YouTube
Complete Python Programming for AI: A Comprehensive Guide to Getting StartedWelcome to this complete Python Programming for Artificial Intelligence (AI)! Wh...
Published: December 11, 2024
Top answer
1 of 2
34

Perhaps it helps if you think of exceptions as tossing and catching balls. One person throws a ball, someone else catches the ball. It's just that some people want to only catch baseballs, while other people only want to catch basketballs, and if someone throws a golfball, perhaps noone is around to catch those..

In that analogy, look at these three snippets of syntax:

  • raise SomeException: throws an exception (a specific type of ball, like throwing only tennis balls).
  • except: catches all exceptions (regardless of type). This is the equivalent of someone catching all ball types, no matter what. If you can throw them a billiard ball, they'll catch it.
  • except SomeException: on the other hand only catches a specific type of exception (like someone that'll only catch baseballs and will ignore anything else).

Then, the following code

try:
    # ...
except:
    raise ZeroDivisionError

does two, separate things. First, it catches all exceptions. And when it has caught an exception, it then raises a new exception.

It's as if someone is standing in a sportsfield, and catches basketballs, baseballs, tennisballs, billiard balls, anything you throw at it, but every time they catch a ball they then will, without fail, throw a golfball at the referee. Nothing else, only golfballs.

That's not the case in this example:

try:
    # ...
except ZeroDevisionError:
    # ...

That's someone only catching golfballs. They are not throwing anything, they are only catching, and only golfballs. Basketballs, baseballs and tennisballs are ignored. That's not the same thing as catching everything, and no throwing is going on.

Finally:

raise SomeException

can be used in any Python code. Code is allowed to throw balls if they feel the need to. You don't need to be catching balls at the same time.

Exceptions are used to break out of the normal flow. For example, you can count on the int() function only ever returning an integer value. When it can't return a value, because something is wrong, it'll raise an exception instead. That way you know it couldn't return a proper integer, because things were wrong somehow. int("Hello world!") can't return an integer value (what would the value be?) so a ValueError exception is raised. When you write your own code, you'll also come across situations where you can't produce a normal, valid response either, so that's when you'd use raise yourself.

And catching all exceptions, with a blanket except:, is usually not what you want to do. I call that playing Pokemon, but you should not play Pokemon when writing good Python code. Because catching all exceptions means you also catch KeyboardInterrupt and MemoryError, things that you normally would want to let the program just end. And you'd catch simple errors caused by programming mistakes. You want to catch specific exceptions only, usually.

2 of 2
7

except is used within a try-except statement, meaning there is an error within your code that caused this exception to be raised. Raise is used for signaling an exception that you want to point out. An example:

for x in range(5):
  if x < 3:
    raise Exception('x is less than 3')
  else:
    print('x is 3 or higher')

In other words, your code will not be broken/will still run even if you don't signal your own exception, whereas if you were to remove a try-except statement from your code, and exception would be raised because of some error (ValueError, AssertionError, etc.). You cannot raise a system exception as you do in the first section of code you posted, only the second will work for properly dealing with error statements issued by python itself.

🌐
Bugsink
bugsink.com › blog › using-raise-from-none-in-python
When to use “raise from None” in Python
December 27, 2024 - How: Simply use raise Exception("message") from None to raise an exception without chaining it to the previous one. By default, Python automatically chains exceptions when one is raised during the handling of another.
🌐
Composingprograms
composingprograms.com › pages › 33-exceptions.html
3.3 Exceptions
The Python interpreter raises an exception each time it detects an error in an expression or statement.
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.

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.

🌐
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.