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.

try:
    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:

fruits = ['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.

fruits = ['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:

fruits = ['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!
Answer from Cblopez on Stack Overflow
🌐
W3Schools
w3schools.com › python › python_try_except.asp
Python Try Except
The try block lets you test a block of code for errors.
🌐
Python documentation
docs.python.org › 3 › tutorial › errors.html
8. Errors and Exceptions — Python 3.14.7 documentation
Exception can be used as a wildcard that catches (almost) everything. However, it is good practice to be as specific as possible with the types of exceptions that we intend to handle, and to allow any unexpected exceptions to propagate on. The most common pattern for handling Exception is to print or log the exception and then re-raise it (allowing a caller to handle the exception as well): import sys try: f = open('myfile.txt') s = f.readline() i = int(s.strip()) except OSError as err: print("OS error:", err) except ValueError: print("Could not convert data to an integer.") except Exception as err: print(f"Unexpected {err=}, {type(err)=}") raise
Discussions

Explain Try / Except structure in practical examples?
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. More on reddit.com
🌐 r/learnpython
21
7
March 23, 2024
Utilizing a Try / Catch method for Python Function Error Catching
This portion works perfectly. I am wanting to implement a try/catch block for the python section so if the user Samaccount is not found that it will display a message letting the admin know that it could not find the users account and terminate the program. I have implemented the ... More on forum.uipath.com
🌐 forum.uipath.com
2
0
December 16, 2022
python - What is more Pythonic way to handle try-except errors? - Software Engineering Stack Exchange
Neither of these is more Pythonic than the other. The examples are too trivial to say which is preferrable but it really all depends on how things should work. Catch and logging/reporting an issue is just a hair's breadth away from squashing exceptions which is almost always a terrible idea. More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
November 1, 2023
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
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.

try:
    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:

fruits = ['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.

fruits = ['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:

fruits = ['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.)


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)
🌐
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 ...
🌐
UiPath Community
forum.uipath.com › help › activities
Utilizing a Try / Catch method for Python Function Error Catching - Activities - UiPath Community Forum
This portion works perfectly. I am wanting to implement a try/catch block for the python section so if the user Samaccount is not found that it will display a message letting the admin know that it could not find the users account and terminate the program. I have implemented the ...
Published: December 16, 2022
Find elsewhere
🌐
YouTube
youtube.com › corey schafer
Python Tutorial: Using Try/Except Blocks for Error Handling - YouTube
We've all run into errors and exceptions while writing Python programs. In this video, we will learn how we can handle exceptions in specific ways and also l...
Published: November 13, 2015
Views: 310K
Top answer
1 of 3
5

Neither of these is more Pythonic than the other. The examples are too trivial to say which is preferrable but it really all depends on how things should work.

Catch and logging/reporting an issue is just a hair's breadth away from squashing exceptions which is almost always a terrible idea. The only reason I can see doing this is that you want whatever the issue is to not stop execution. If you are going to do something like this, it's really crucial to make sure that you return something sensible that works for the caller. If the next thing that happens is that the calling code throws its own exception because e.g., None doesn't have an add method, you are at best just making things harder to troubleshoot. It could be a lot worse, however. A lot of serious bugs are due to returning nulls/None after catching an error. I think there are times that is makes sense to do this, but they are rare in my experience.

Allowing the raw exception to bubble out is the next least-worst option, IMO. This can be fine if you are building something small where it will be easy to find the what the problem is when things crash with a KeyError. In a situation where you are leveraging a lot of duck-typing, passing around function references, or using annotations, it can sometimes be difficult. For example, if you are using this code behind a web endpoint, what HTTP error code should you use when you catch a KeyError. 500 might be the right answer in most cases but there might be times you want to produce something else depending on where the key was not found.

That brings me to the last option which you don't mention: catch and raise a separate, more meaningful error. That allows you to distinguish between say, a KeyError thrown because the request was for something that isn't valid and a KeyError thrown because of a bad configuration.

2 of 3
4

Neither is pythonic. Pythonic code would be:

my_dict = {}
def fetch_value(key):
    return my_dict[key]

val = fetch_value('my_key')

Remember, simple is better than complex and flat is better than nested. Since your except-block does not handle the exception in any meaningful way, it is better to just let it bubble up the call stack and terminate the program.

But in your code the error is ignored and it implicitly returns None if the key is not found. If this is what you want, then it can be done simpler with the get() method:

def fetch_value(key):
    return my_dict.get(key)

"Handling" an error by just logging a message and then continuing as if nothing happened, is a terrible antipattern from the Java world which has no place in Python. Exceptions should only be caught if they can be meaningfully handled.

🌐
Real Python
realpython.com › python-exceptions
Python Exceptions: An Introduction – Real Python
March 18, 2026 - You can have more than one function call in your try clause and anticipate catching various exceptions. Something to note here is that the code in the try clause will stop as soon as it encounters any one exception. Warning: When you use a bare except clause, then Python catches any exception that inherits from Exception—which are most built-in 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.

Top answer
1 of 5
5
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.
2 of 5
3
I wrote the example below for another question not too long ago. (With logging and custom exceptions) And I think it will be enlightening to your question but not answer it directly. So there is copy/paste. The best practice is to know what would throw, handle it or let it raise. import logging #Basic logger setup logger = logging.getLogger(__name__) logging.basicConfig(filename=‘example.log’, encoding=‘utf-8’, level=logging.DEBUG) def can_throw(user, *args): “This function raises exceptions because of an internal call that requires authorization, those exceptions should remain, so we log and handle them.” try: #error prone code …. #Custom Error Handled except MissingApproval: #User has to be manually approved by management but can use this function temporarily, logged for records. e.g. New Hires, contract expirations, department changes logger.info(f”{user.name} approval override, can_throw(), check current job status.”) #recursive call temp approval user.approval = True res = can_throw(user, *args) user.approval = False return res #Custom Error Exit() #yes we can have multiple excepts except Termination: # User can not use this function if has been terminated before. Expected to fail. logger.warn(f”{user.name} : {user.id} attempted to use can_throw({args}), UNAUTHORIZED, and DENIED”) print(“You do not have authorization to use this function”) #pause with input() for user to read msg. input(“Press [enter] to close”) exit() #Catch All Friendly Close except Exception as e: #log full stacktrace error logger.error(e, stack_info = True, exc_info = True) #log user id, and args for quick reference logger.error(f”Function: can_throw({user.id}, {args})) #Friendly message. print(“Something went wrong with can_throw()”) print(“This error has been logged for review, sorry for the inconvenience.) input(“Press [enter] to close”) exit() Note: this is still answering another question. To do with exceptions with logging, kept because good info as well Fairly straightforward logging. You have to flag for the stacktrace, and the Python exc_info explanations, e.g. “list index out of range” (you could probably just use logger.exception(e) as well) Just read the documentation, you most likely won’t really need much more complicated stuff here. Generally speaking the best practice is to already know which errors can be thrown, look above, I’m catching individual errors and handling them differently, do that! and try not use the generic ‘Exception’, . (That’s kind of hard though when you start.) Then if it crashes let the crash tell you where, and handle that error for next time. You may need to use the general exception to find more about the crash on a top level, but in the code you should be handling all expected exceptions. We also can’t forget sometimes raising is the correct response. raise MissingApproval(“Sorry, you do not have authorization to use this function”) >>>Stacktrace… …. >>>MissingApproval : Sorry, you do not have authorization to use this function Can do a lot. And is simpler. And is probably reminiscent of something, you’ve seen before…. And we’re done. Without everything above for other functions.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-try-except
Python Try Except - GeeksforGeeks
June 8, 2026 - A try statement can contain multiple except blocks to handle different types of errors. ZeroDivisionError: Raised when dividing a number by zero. ValueError: Raised when a function receives an invalid value. TypeError: Raised when an operation is performed on incompatible data types. FileNotFoundError: Raised when a file does not exist. ImportError: Raised when Python cannot import a module.
🌐
Mimo
mimo.org › glossary › python › try-except
Mimo: The coding platform you need to learn Web Development, Python, and more.
Start your coding journey with Python. 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)
🌐
YouTube
youtube.com › watch
Try / Except | Python | Tutorial 27 - YouTube
Source Code - http://www.giraffeacademy.com/programming-languages/python/ This video is one in a series of videos where we'll be looking at programming in py...
Published: October 22, 2017
🌐
Python Land
python.land › home › language deep dives › python try except: examples and best practices
Python Try Except: Examples And Best Practices • Python Land Tutorial
January 29, 2026 - According to the Python manual, using the else clause is better than adding additional code to the try clause. But why? The reasoning is that it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try and except statements in the first place.
🌐
Quora
quora.com › How-do-you-handle-a-try-catch-in-Python
How to handle a try catch in Python - Quora
Answer (1 of 2): You mean how do you handle an exception in Python ? Try/catch us a Java (?) construct for dealing with exceptions. In Python the construct is try/except (Tutorial documentation here 8. Errors and Exceptions). The format is simple - an example: [code]data = [10,13,17,9,12, 23] ...
🌐
Medium
galea.medium.com › pythons-try-except-else-finally-explained-f04d47d57125
Python’s “try except else finally” explained | by Alexander Galea | Medium
October 4, 2020 - The idea in my example above is to write the div text to a file only if it’s found on the page. It’s important to do this after the try block runs, to avoid the except block catching any file handling error that may arise.
🌐
Python.org
discuss.python.org › python help
[SOLVED]How to catch error signals without try / except - Python Help - Discussions on Python.org
December 19, 2021 - Hi, First time posting here. I’d like to catch any error signal produced, be it a NameError, IndentationError, or whatnot. I don’t care to escape them, I would just like to be able to call some simple function whenever such an error occurs. Some people might say that this is a bad idea, ...
🌐
Rollbar
rollbar.com › home › when to use try-except vs. try-catch
When to Use Try-Except vs. Try-Catch | Rollbar
Both share a similar philosophy ... a designated way. There's one big difference between them though: try-except is for Python while try-catch is for Java....
Published: July 31, 2023
🌐
Tutorialspoint
tutorialspoint.com › python › python_exceptions.htm
Python - Exceptions Handling
Note: In order to catch an exception, an "except" clause must refer to the same exception thrown either class object or simple string. For example, to capture above exception, we must write the except clause as follows − · try: Business Logic here... except "Invalid level!": Exception handling here... else: Rest of the code here... Python also allows you to create your own exceptions by deriving classes from the standard built-in exceptions.