except as err: doesn't work because the correct syntax is:

except TypeOfError as somename:

To catch any type of error, use Exception as the type, it is the common base class for all non-exit exceptions in Python:

try:
    # Error generating code
except Exception as err:
    print(err)

err will be an instance of the actual exception that was raised, you can see its correct type with type(err), and it's attributes and methods with dir(err).

Keep in mind that it's recommended to use the most specific type of exception that may be raised.

See more details in Python's tutorial on error handling.

Answer from janos on Stack Overflow
🌐
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.7 documentation
When an exception occurs, it may have associated values, also known as the exception’s arguments. The presence and types of the arguments depend on the exception type. The except clause may specify a variable after the exception name.
Discussions

python - usage of except and store error in a variable - Stack Overflow
I need to catch all the ... it in a variable. I want something like this: try: Error generating code except as err: print err · But this doesnt work. Is there any other way to do the same? ... To catch any type of error, use Exception as the type, it is the common base class for all non-exit exceptions in Python... More on stackoverflow.com
🌐 stackoverflow.com
python - How to make a variable inside a try/except block public? - Stack Overflow
As answered before there is no new scope introduced by using try except clause, so if no exception occurs you should see your variable in locals list and it should be accessible in current (in your case global) scope. More on stackoverflow.com
🌐 stackoverflow.com
November 17, 2017
assign a global variable in try/except
If you are trying to change a global variable from an inner scope, then in that inner scope you need to have global company. Sometimes it can't be avoided but doing so is usually a "code smell" More on reddit.com
🌐 r/learnpython
5
1
September 7, 2017
Scope of a variable
I am new in python coding and I just don't understand why I did not received an error message when I use the variables "a" and "b" in the "else" block. What I expected is to received an error since the variables "a" and "b" is inside the "try" block, I am assumed that I can only use those variable inside the "try" block. Thank you in advance. def add (num1, num2): try: a = float(num1) b = float(num2) except ... More on teamtreehouse.com
🌐 teamtreehouse.com
2
February 18, 2018
🌐
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.
🌐
Python
bugs.python.org › issue43458
Issue 43458: Tutorial should mention about variable scope in try/except/finally - Python tracker
March 10, 2021 - This issue tracker has been migrated to GitHub, and is currently read-only.
Top answer
1 of 3
145

try statements do not create a new scope, but text won't be set if the call to url lib.request.urlopen raises the exception. You probably want the print(text) line in an else clause, so that it is only executed when there is no exception.

try:
    url = "http://www.google.com"
    page = urllib.request.urlopen(url)
    text = page.read().decode('utf8')
except (ValueError, RuntimeError, TypeError, NameError):
    print("Unable to process your request dude!!")
else:
    print(text)

If text needs to be used later, you really need to think about what its value is supposed to be if the assignment to page fails and you can't call page.read(). You can give it an initial value prior to the try statement:

text = 'something'
try:
    url = "http://www.google.com"
    page = urllib.request.urlopen(url)
    text = page.read().decode('utf8')
except (ValueError, RuntimeError, TypeError, NameError):
    print("Unable to process your request dude!!")

print(text)

or in the else clause:

try:
    url = "http://www.google.com"
    page = urllib.request.urlopen(url)
    text = page.read().decode('utf8')
except (ValueError, RuntimeError, TypeError, NameError):
    print("Unable to process your request dude!!")
else:
    text = 'something'

print(text)
2 of 3
10

As answered before there is no new scope introduced by using try except clause, so if no exception occurs you should see your variable in locals list and it should be accessible in current (in your case global) scope.

print(locals())

In module scope (your case) locals() == globals()

🌐
Reddit
reddit.com › r/learnpython › assign a global variable in try/except
r/learnpython on Reddit: assign a global variable in try/except
September 7, 2017 -

Hej guys. I have a problem assign a global variable inside a try/except. The try/except is in the main function and iam using the variable in another function. when i print the variable outside the main function i get "something" instead of the assigned value. how can i solve it?

company ="something"  #global variable

               try:
                    loggInThisFile = open(reportFilePath,'w')
                except Exception as e:
                    print("can't create report file:", reportFilePath)
                else:
                    company = link.split(" ; ")[1]
                    print(company)     #prints assigned value 

ps: the declaration and assignation is done before it soposed to be used.
Thanks in advance

Find elsewhere
🌐
Educative
educative.io › answers › what-is-a-try-except-block-in-python
What is a try-except block in python?
except: print("Seeems like something else went wrong") Run · The following code explains how else block gets executed when the try executed correctly: try: variable="Python Programming"; print(variable) except: print("An exception occurred") else: print("Else executes: Try block executed correctly") Run ·
🌐
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 - Just like well-named variables and functions, a well-named exception can be a big difference when reading back your code. We’ll use this class in the example that follows. We know some built-in exceptions and how to create custom exceptions. We also know how to catch exceptions with try and except.
🌐
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 ...
🌐
Python Basics
pythonbasics.org › home › python basics › try and except in python
Try and Except in Python - pythonbasics.org
All exceptions in Python inherit from the class BaseException. If you open the Python interactive shell and type the following statement it will list all built-in exceptions: ... The idea of the try-except clause is to handle exceptions (errors at runtime).
🌐
freeCodeCamp
freecodecamp.org › news › exception-handling-python
How to Handle Exceptions in Python: A Detailed Visual Introduction
December 22, 2019 - Here we have an example (see below) were we assign the instance of ZeroDivisionError to the variable e. Then, we can use this variable within the except clause to access the type of the exception, its message, and arguments. def divide_integers(): while True: try: a = int(input("Please enter the numerator: ")) b = int(input("Please enter the denominator: ")) print(a / b) # Here we assign the exception to the variable e except ZeroDivisionError as e: print(type(e)) print(e) print(e.args) divide_integers()
🌐
Reddit
reddit.com › r/learnpython › help: can you create a variable that is a try/exception block?
r/learnpython on Reddit: Help: Can you create a variable that is a try/exception block?
January 9, 2022 -

I have some code that pulls stock information into an excel sheet using the tickers present in the excel file, and I recently am trying to expand this code to pull in the stocks sectors using yfinance. The issue is that some of my tickers are EFT's, which do not have sectors. So whenever my code tries to run, it will throw a syntax error when it reaches an EFT stock. If I take out all the EFT's, it runs just fine.

What I'm trying to do is set my variable (sector) as a try/exception block, but I don't know if this is possible. Could someone please help me out on this? Examples or suggestions? I'm not exactly new to Python, but I'm not a regular program either. Just really lost and in hard core struggle mode on this one.

Excerpt from my code below, along with what I'm having trouble with developing below that.

import xlwings as xw
from yahoofinancials import YahooFinancials
import pandas as pd
import yfinance as yf

def main():
    wb = xw.Book.caller()
    sheet = wb.sheets[0]
    df = pd.DataFrame()
    tickers = sheet.range("D7").options(expand='down').value
    for ticker in tickers:
        find_sector = yf.Ticker(ticker)
        sector = find_sector.info['sector']

        new_row = {
            "GICS Sector": sector,
        }
        df = df.append(new_row, ignore_index=True)
    sheet.range("E6").options(index=False).value = df

if __name__ == "__main__":
    xw.Book("dividends.xlsm").set_mock_caller()
    main()

What I'm envisioning/trying/struggling with for setting my 'sector' variable:

sector =
    try:
        find_sector.info['sector']
    else:
        print('EFT')
🌐
NetworkLessons
networklessons.com › home › python › python try except
Python Try Except
The try block didn’t run into exceptions and we executed the else statement. Here is one more example: try: print(my_variable) except: print("Variable does not exist.") else: print("Everything is OK.")
Published: August 7, 2026
🌐
UTK
web.eecs.utk.edu › ~bvanderz › cs365 › notes › Python › PythonExceptionHandling.html
exception handling
except Exception, variable so if you omit the parentheses in the above statement, Python will try to bind the variable named TypeError to the exception object for RuntimeError, which is not what you intend.
🌐
Note.nkmk.me
note.nkmk.me › home › python
Try, except, else, finally in Python (Exception handling) | note.nkmk.me
August 15, 2023 - ... For example, when attempting ... # ZeroDivisionError: division by zero ... By using except <exception-name> as <variable-name>:, the exception object is stored in the variable....
🌐
StrataScratch
stratascratch.com › blog › understanding-python-try-except-blocks
Understanding Python Try Except Blocks - StrataScratch
October 10, 2023 - In this code, we have a try block where we try dividing 10 by 0, an operation that will certainly cause a ZeroDivisionError. Fortunately, we have guessed this error and have set up an except block to catch it, preventing the program from crashing and assigning an error message to the result variable.
🌐
Stack Overflow
stackoverflow.com › questions › 51318203 › try-except-exception-as-variable
python - try .. except Exception as <variable> - Stack Overflow
My question is, how can I access the other keys within that object given that I can't seem to assign the results of that call within python in the case of a failure (i.e. data = <pythonic api call> won't work), and within except I can only seem to access the value from the "error_message" key? Ideally, I would like to access the entire object under the "status: "fail" scenario somehow. ... myVariable contains an exception object that shows only the message when you try to print it.