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 Overflowpython - usage of except and store error in a variable - Stack Overflow
python - How to make a variable inside a try/except block public? - Stack Overflow
assign a global variable in try/except
Scope of a variable
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)
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()
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
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')try:
1 / 0
except Exception as e:
print(e)
If you're expecting a DivideByZero error, you can catch that particular error
import traceback
try:
x = 5
y = 0
print x/y
except ZeroDivisionError:
print "Error Dividing %d/%d" % (x,y)
traceback.print_exc()
except:
print "A non-ZeroDivisionError occurred"
You can manually get the line number and other information by calling traceback.print_exc()