try:
    do_something()
except:
    pass

You will use the pass statement.

The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action.

Answer from Andy on Stack Overflow
🌐
Stack Overflow
stackoverflow.com › questions › 72298793 › is-it-okay-to-leave-except-empty-when-i-print-out-trackback-anyway-python-3-1
Is it okay to leave except EMPTY, when I print out trackback anyway? [Python 3.10] - Stack Overflow
I understand that it's usually not a good idea to leave "except" empty as errors will go unnoticed. For example: def test4(): try: 0/0 except: pass print('PROG...
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)
🌐
CodeQL
codeql.github.com › codeql-query-help › python › py-empty-except
Empty except — CodeQL query help documentation
An empty except block may be an indication that the programmer intended to handle the exception, but never wrote the code to do so. Ensure all exceptions are handled correctly. In this example, the program keeps running with the same privileges if it fails to drop to lower privileges.
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 72007659 › how-do-i-avoid-except-returning-an-empty-object-class
python - How do I avoid except returning an empty object class - Stack Overflow
April 26, 2022 - My initial solution was using sys.exit, ... would be except InputError: rm = None. So rather than creating an "empty" object, create a null object....
🌐
DaniWeb
daniweb.com › programming › software-development › threads › 381248 › using-try-except-to-catch-a-blank-input
python - Using Try, Except to catch a blank input [SOLVED] | DaniWeb
In python 3, after result = input(prompt) , result is a string in the python sense (an instance of the datatype 'str'). Examples of strings are · "" # the empty string " " # a string of white space "3.14159" # a string with the representation … — Gribouillis 1,391 Jump to Post · You can pass the acceptable values to the checkInput() function and let it do the work. For the getFloat() function, use a try/except to test for correct input.
🌐
Java2s
java2s.com › example › python-book › catching-all-the-empty-except-and-exception.html
Python - Catching all: The empty except and Exception
try: action() except NameError: ... # Handle NameError except IndexError: ... # Handle IndexError except: ... # Handle all other exceptions else: ... # Handle the no-exception case · The empty except clause is a sort of wildcard feature.