So think of it this way. Your program is perfect. Prestige. Internally you can totally control interactions, account for mishaps, etc. But! There are outside forces that you can't outright account for, like: An API that is sometimes reachable. And requests crashes An application that you've wrapped in python code A database connection that fails because someone rebooted the server You'll want to be reactive in these cases instead of seeing a traceback. If you expect certain failures and not others you can get more specific and catch certain exceptions. In an imperfect world they're helpful. Answer from Arkrus on reddit.com
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_try_except.asp
Python Try Except
try: print(x) except NameError: print("Variable x is not defined") except: print("Something else went wrong") Try it Yourself ยป ยท See more Error types in our Python Built-in Exceptions Reference.
๐ŸŒ
Python documentation
docs.python.org โ€บ 3 โ€บ tutorial โ€บ errors.html
8. Errors and Exceptions โ€” Python 3.14.5 documentation
Look at the following example, which asks the user for input until a valid integer has been entered, but allows the user to interrupt the program (using Control-C or whatever the operating system supports); note that a user-generated interruption is signalled by raising the KeyboardInterrupt exception. >>> while True: ...
Discussions

try catch - How to work with try and except in python? - Stack Overflow
This program has to analyze student numbers and if they are correct write them to one list and if not write them to another list. They are correct if they have eight digits and contain only numbers... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Best practices for try/except blocks in Python script.
I am thinking that Approach 2 might be the best approach for my problem. Yep, you nailed it. This is exactly what you should do. More on reddit.com
๐ŸŒ r/learnpython
16
6
September 20, 2024
I'm new to Try and Except clauses. I don't understand why this code doesn't work.
Three comments: You can format code blocks in Reddit (if you are on Fancy Pants editor, click the three dots, and it will show you). Especially in Python, indentation and formatting are important, so please use it in the future. This code is working for me. I don't know what the issue is. Your error message is from an online tutoring thing, so it's not actually useful. Check that your indentations are all consistent. It is also possible that there is an error in the hidden test code like they say. Don't use bare except like this. In this case, what you are guarding against is an IndexError where your index (4) is larger than the size of the string. So instead do: food = ["chocolate", "chicken", "corn", "sandwich", "soup", "potatoes", "beef", "lox", "lemonade"] fifth = [] for x in food: try: fifth.append(x[4]) except IndexError: pass print(fifth) (this is the code block I mentioned) Maybe try this code catching the specific exception. Perhaps that is what they were testing for. More on reddit.com
๐ŸŒ r/learnpython
19
1
June 21, 2021
Try and Except... Is there a way to make except loop back to a specific point.
You need to put the while clause where you want the loop to go back to. That is, the while clause should probably be somewhere before the try. while True: # get input from user # try to convert it to a number # except when there's a problem # show an error message # restart the loop # else stop the loop More on reddit.com
๐ŸŒ r/learnpython
11
May 22, 2014
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ explain try / except structure in practical examples?
r/learnpython on Reddit: Explain Try / Except structure in practical examples?
March 23, 2024 -

I am learning python and I've encountered the try / except part of it. I am struggling to understand when I would use this kind of code, probably because I am still very new and most of my code is small programs that have relied on conditional statments.

I guess in my brain I understand the logic of saying "try to do this but if it doesn't work just let it be and keep going with the code". My assumption is this is helpful on larger scale programs in wich you can't afford the time to make sure the code is fail proof and you need the code to buy you time to eventually go back once you have the fail proof option?

Was hoping someone could give me an example of a real life application or website and how this code could apply to it? Because I want to become comfortable with it but unsure how to.

TL,DR: Explain try/except in a practical example so I can understand when and where I would use it?

Thank you!

๐ŸŒ
Berkeley
pythonnumericalmethods.studentorg.berkeley.edu โ€บ notebooks โ€บ chapter10.03-Try-Except.html
Try/Except โ€” Python Numerical Methods
More specifically, the error or exception must not cause a critical error that makes your program shut down. A Try-Except statement is a code block that allows your program to take alternative actions in case an error occurs. ... Python will first attempt to execute the code in the try statement ...
๐ŸŒ
Medium
galea.medium.com โ€บ pythons-try-except-else-finally-explained-f04d47d57125
Pythonโ€™s โ€œtry except else finallyโ€ explained | by Alex Galea | Medium
October 4, 2020 - Pythonโ€™s โ€œtry except else finallyโ€ explained In Python itโ€™s okay to make assumptions, as long as youโ€™re able to clean up the mess if they turn out to be wrong. In fact, this is not only โ€ฆ
Top answer
1 of 3
25

Okey, so there a few things that need to be explained where.

What is try-except used for?

It is used for catching errors raised by the program. Any code susceptible of raising an exception is inserted inside a try statement, and below that statement, any number of except statements with any single error that you want to catch.

Copytry:
    user_input = int(input('Give me a number: '))
except ValueError:
    print('That is not a number!')

When should i use try-except?

It is not a good practice to use a try-except on every single line of code that could raise an error, because that may be half of it, or more. So when shall you use it? Simple, ask this question: Do I want to do any custom action with that error being raised? If the answer is yes, you are good to go.

Catching Exception or empty except

As I see in your example, you are using an empty except. Using an empty except statement will catch every single error raised that the surrounded code, which is similar (but not the same) as catching Exception. The Exception class is the superclass of every single built-in exception in the Python environment that are non-system-exiting (read here) and its generally a bad practice to catch either all exceptions with except: or Exception with except Exception:. Why? Because you are not letting the user (or even you, the programmer) know what error you are handling. For example:

Copyfruits = ['apple', 'pear', 'banana']
try: 
    selection = fruits[int(input('Select a fruit number (0-2): '))]  
except Exception:
    print('Error!')
    # But wait, are you catching ValueError because the user did not input a number, 
    # or are you catching IndexError because he selected an out of bound array index? 
    # You don't know  

Catching multiple exceptions

Based on the previous example, you can use multiple try-except statements to difference which errors are being raised.

Copyfruits = ['apple', 'pear', 'banana']
try: 
    selection = fruits[int(input('Select a fruit number (0-2): '))]  
except ValueError:
    print('That is not a number')
except IndexError:
    print('That fruit number does not exist!')  

Grouping exceptions

If there are two particular exceptions that you want to use for a same purpose, you can group them in a tuple:

Copyfruits = ['apple', 'pear', 'banana']
try: 
    selection = fruits[int(input('Select a fruit number (0-2): '))]  
except (ValueError, IndexError):
    print('Invalid selection!')  

Your case

Based on this information, add those try-except blocks to your code, and see what possible errors that could be raised during its execution, asking the previously recommended question Do I want to execute some custom action with this error?

Additionally

  • There are try-except-else statements. See here
  • There are try-except-finally statements. See here
  • You can combine them all in a try-except1-except2...exceptN-else-finally statement.
  • I recommend you get familiar with built-in errors why practicing this!
2 of 3
0
  1. try: code that might cause an error

  2. except: code that runs if an error happens

  3. else: runs if no error happens

  4. finally: always runs (good for cleanup, closing files, etc.)

Copy
Example 1: Basic Example
try:
    num = int("abc")   # This will raise an error
    print("Number:", num)
except ValueError:
    print("Oops! Could not convert to int.")


Example 2:

try:
    x = 10 / 0
except ZeroDivisionError:
    print("You cannot divide by zero!")
except ValueError:
    print("Invalid value!")

Example 3:
try:
    x = 5 / 1
except ZeroDivisionError:
    print("Division by zero not allowed.")
else:
    print("Division successful:", x)   # runs if no error
finally:
    print("Always runs, even if there was an error.")

Example 4: General 
try:
    # risky code
    x = 10 / 0
    y = int("abc")
except Exception as e:
    print("Error occurred:", e)
Find elsewhere
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-try-except
Python Try Except - GeeksforGeeks
July 23, 2025 - try: # Some Code except: # Executed if error in the # try block else: # execute if no exception finally: # Some code .....(always executed) ... # Python program to demonstrate finally # No exception Exception raised in try block try: k = 5//0 # raises divide by zero exception.
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ error-handling-in-python-introduction
Error Handling in Python โ€“ try, except, else, & finally Explained with Code Examples
September 1, 2024 - Lines 4 and 5 open an except clause for any ZeroDivisionError and instruct the program to print a message should we try to divide anything by 0 ยท You likely notice the issue. My variable x has the value 0, and I am trying to divide 5 by x. The best mathematicians in the world canโ€™t divide by 0, and neither can Python.
๐ŸŒ
X
x.com โ€บ polydao โ€บ status โ€บ 2047665050610028916
My friend was rejected from Google 3 times > 4th try
My friend was rejected from Google 3 times > 4th try: $185,000 offer. nothing changed except one thing > he found out Claude Code Skills exist on his $20 Pro plan > spent a weekend setting them up > showed up to the take-home and built something that looked like a full team >
๐ŸŒ
Python
peps.python.org โ€บ pep-0008
PEP 8 โ€“ Style Guide for Python Code | peps.python.org
The first form means that the name of the resulting function object is specifically โ€˜fโ€™ instead of the generic โ€˜<lambda>โ€™. This is more useful for tracebacks and string representations in general. The use of the assignment statement eliminates the sole benefit a lambda expression can offer over an explicit def statement (i.e. that it can be embedded inside a larger expression) Derive exceptions from Exception rather than BaseException.
๐ŸŒ
Mimo
mimo.org โ€บ glossary โ€บ python โ€บ try-except
Mimo: The coding platform you need to learn Web Development, Python, and more.
Learn basics, data types, control flow, and more ... try: # Code that might raise an exception except SomeException as e: # Code that runs if the exception occurs else: # Code that runs if no exception occurs (optional) finally: # Code that always runs, regardless of exceptions (optional)
๐ŸŒ
Python-Fiddle
python-fiddle.com โ€บ tutorials โ€บ try-except
Error Handling with Try-Except in Python
- **`except ZeroDivisionError`**: Catches and handles the `ZeroDivisionError`. ### Catching Specific Exceptions You can catch [different types of exceptions](/tutorials/exceptions) and handle them separately. try: # Risky code result = int('abc') except ValueError: # Code to run if a ValueError occurs print("A value error occurred: invalid literal for int()") except TypeError: # Code to run if a TypeError occurs print("A type error occurred.")
๐ŸŒ
Medium
medium.com โ€บ @ifeoluwapraise02 โ€บ how-to-implement-error-handling-in-python-with-try-except-blocks-3e6708bce4ca
How to Implement Error Handling in Python with Try-Except Blocks | by Praise Idowu | Medium
September 26, 2023 - You could also use the Exception block to generalize every error. ... There are also cases where you want to print the error message instead of a different message in the output. try: result = '5' + 2 print(result) except TypeError as e: print('error', e)
๐ŸŒ
Towards AI
pub.towardsai.net โ€บ how-i-use-python-to-automate-80-of-my-power-bi-workflow-full-scripts-included-d04b23fe5fd5
How I Use Python to Automate 80% of My Power BI Workflow (Full Scripts Included) | by Gulab Chand Tejwani | Apr, 2026 | Towards AI
April 13, 2026 - How I Use Python to Automate 80% of My Power BI Workflow (Full Scripts Included) My clientโ€™s analytics team was spending 15+ hours every week on manual Power BI tasks โ€” triggering refreshes โ€ฆ
๐ŸŒ
Programiz
programiz.com โ€บ python-programming โ€บ exception-handling
Python Exception Handling (With Examples)
Since exceptions abnormally terminate the execution of a program, it is important to handle exceptions. In Python, we use the try...except block to handle exceptions.
๐ŸŒ
Real Python
realpython.com โ€บ python-exceptions
Python Exceptions: An Introduction โ€“ Real Python
December 1, 2024 - Exceptions in Python occur when syntactically correct code results in an error. The try โ€ฆ
๐ŸŒ
Udacity
udacity.com โ€บ blog โ€บ 2021 โ€บ 09 โ€บ getting-started-with-try-except-in-python.html
Getting started with try/except in Python | Udacity
September 9, 2021 - Python provides a number of built-in exceptions, and libraries are free to extend the Exception class to implement their own. We use the try and except keywords to catch, or handle, exceptions.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ best practices for try/except blocks in python script.
r/learnpython on Reddit: Best practices for try/except blocks in Python script.
September 20, 2024 -

I am writing a python script to interact with an instrument. The instrument comes with a python library that I am using in my script.

I am not sure what might be the best practice for using try/except blocks in Python.

Approach 1:

try:
    some_command_1
except Exception as e:
    logger.exception(e)

try:
    some_command_2
except Exception as e:
    logger.exception(e)
.
.
.
try:
    some_command_n
except Exception as e:
    logger.exception(e)

Approach 2:

def main():
    command_1()
    command_2()
    command_n()

if __name__ == "__main__":
    try:
        main()
    except Exception as e:
        logger.exception(e)

When there is an error that raises to a level of an exception, I don't want my script to just catch the exception and move on to the next step.

The step where this error could have occurred might be critical that it is not necessary to proceed with the execution of the remainder of the script.

I am thinking that Approach 2 might be the best approach for my problem. But is it a good practice to do it this way?

The type of error that raises to the level of exception include: Instrument has a problem that it doesn't want to execute the command, lost communications etc.

๐ŸŒ
Server Academy
serveracademy.com โ€บ blog โ€บ python-try-except
Python Try Except - Blog - ServerAcademy.com
When writing Python code, errors can be frustrating. Luckily, Pythonโ€™s and blocks provide an effective way to manage errors without breaking the flow of your co
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ glossary.html
Glossary โ€” Python 3.14.5 documentation
Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements.