Skip to content

Commit da55f70

Browse files
committed
Remove old-style sys.exc_info usage in favor of caught exception
1 parent ddc14b2 commit da55f70

File tree

24 files changed

+111
-148
lines changed

24 files changed

+111
-148
lines changed

AutoDuck/makedfromi.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -83,9 +83,8 @@ def make_doc_summary(inFile, outFile):
8383
curMethod[1].append("// " + doc + "\n")
8484
else:
8585
extra_tags.append("// " + doc + "\n")
86-
except:
87-
_, msg, _ = sys.exc_info()
88-
print("Line %d is badly formed - %s" % (lineNo, msg))
86+
except Exception as msg:
87+
print(f"Line {lineNo} is badly formed - {msg}")
8988

9089
lineNo += 1
9190

@@ -150,10 +149,9 @@ def doit():
150149
elif o == "-o":
151150
outName = a
152151
msg = " ".join(args)
153-
except getopt.error:
154-
_, msg, _ = sys.exc_info()
152+
except getopt.error as msg:
155153
print(msg)
156-
print("Usage: %s [-o output_name] [-p com_parent] filename" % sys.argv[0])
154+
print(f"Usage: {sys.argv[0]} [-o output_name] [-p com_parent] filename")
157155
return
158156

159157
inName = args[0]

Pythonwin/pywin/Demos/app/basictimerapp.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -127,12 +127,10 @@ def OnTimer(self, id, timeVal):
127127
try:
128128
exec(self.dlg.doWork)
129129
print("The last operation completed successfully.")
130-
except:
131-
t, v, tb = sys.exc_info()
132-
str = f"Failed: {t}: {v!r}"
130+
except Exception as error:
131+
str = f"Failed: {type(error)}: {error!r}"
133132
print(str)
134133
self.oldErr.write(str)
135-
tb = None # Prevent cycle
136134
finally:
137135
self.ReleaseOutput()
138136
self.dlg.butOK.EnableWindow()

Pythonwin/pywin/Demos/cmdserver.py

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -83,21 +83,15 @@ def ServerThread(myout, cmd, title, bCloseOnEnd):
8383
if bOK:
8484
print("Command terminated without errors.")
8585
else:
86-
t, v, tb = sys.exc_info()
87-
print(t, ": ", v)
88-
traceback.print_tb(tb)
89-
tb = None # prevent a cycle
86+
traceback.print_exc()
9087
print("Command terminated with an unhandled exception")
9188
writer.unregister()
9289
if bOK and bCloseOnEnd:
9390
myout.frame.DestroyWindow()
9491

9592
# Unhandled exception of any kind in a thread kills the gui!
9693
except:
97-
t, v, tb = sys.exc_info()
98-
print(t, ": ", v)
99-
traceback.print_tb(tb)
100-
tb = None
94+
traceback.print_exc()
10195
print("Thread failed")
10296

10397

Pythonwin/pywin/debugger/debugger.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -478,10 +478,8 @@ def RespondDebuggerState(self, state):
478478
val = repr(eval(text, globs, locs))
479479
except SyntaxError:
480480
val = "Syntax Error"
481-
except:
482-
t, v, tb = sys.exc_info()
483-
val = traceback.format_exception_only(t, v)[0].strip()
484-
tb = None # prevent a cycle.
481+
except Exception as error:
482+
val = traceback.format_exception_only(type(error), error)[0].strip()
485483
self.SetItemText(i, 1, val)
486484

487485

Pythonwin/pywin/debugger/fail.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55

66
# It does nothing useful, and it even doesn't do that!
77

8-
import sys
98
import time
109

1110
import pywin.debugger
@@ -15,9 +14,9 @@ def a():
1514
a = 1
1615
try:
1716
b()
18-
except:
17+
except Exception as error:
1918
# Break into the debugger with the exception information.
20-
pywin.debugger.post_mortem(sys.exc_info()[2])
19+
pywin.debugger.post_mortem(error.__traceback__)
2120
a = 1
2221
a = 2
2322
a = 3

Pythonwin/pywin/framework/app.py

Lines changed: 21 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -213,10 +213,10 @@ def OnHelp(self, id, code):
213213
from . import help
214214

215215
help.OpenHelpFile(helpFile, helpCmd)
216-
except:
217-
t, v, tb = sys.exc_info()
218-
win32ui.MessageBox(f"Internal error in help file processing\r\n{t}: {v}")
219-
tb = None # Prevent a cycle
216+
except Exception as error:
217+
win32ui.MessageBox(
218+
f"Internal error in help file processing\r\n{type(error)}: {error}"
219+
)
220220

221221
def DoLoadModules(self, modules):
222222
# XXX - this should go, but the debugger uses it :-(
@@ -280,23 +280,23 @@ def OnDropFiles(self, msg):
280280
# but handles errors slightly better.
281281
# It all still works, tho, so if you need similar functionality, you can use it.
282282
# Therefore I haven't deleted this code completely!
283-
# def CallbackManager( self, ob, args = () ):
284-
# """Manage win32 callbacks. Trap exceptions, report on them, then return 'All OK'
285-
# to the frame-work. """
286-
# import traceback
287-
# try:
288-
# ret = apply(ob, args)
289-
# return ret
290-
# except:
291-
# # take copies of the exception values, else other (handled) exceptions may get
292-
# # copied over by the other fns called.
293-
# win32ui.SetStatusText('An exception occured in a windows command handler.')
294-
# t, v, tb = sys.exc_info()
295-
# traceback.print_exception(t, v, tb.tb_next)
296-
# try:
297-
# sys.stdout.flush()
298-
# except (NameError, AttributeError):
299-
# pass
283+
# def CallbackManager(self, ob, args=()):
284+
# """Manage win32 callbacks. Trap exceptions, report on them, then return 'All OK'
285+
# to the frame-work."""
286+
# try:
287+
# ret = apply(ob, args)
288+
# return ret
289+
# except Exception as error:
290+
# import traceback
291+
#
292+
# # take copies of the exception values, else other (handled) exceptions may get
293+
# # copied over by the other fns called.
294+
# win32ui.SetStatusText("An exception occurred in a windows command handler.")
295+
# traceback.print_exception(type(error), error, error.__traceback__.tb_next)
296+
# try:
297+
# sys.stdout.flush()
298+
# except (NameError, AttributeError):
299+
# pass
300300

301301
# Command handlers.
302302
def OnFileMRU(self, id, code):

Pythonwin/pywin/framework/editor/__init__.py

Lines changed: 35 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -29,37 +29,41 @@
2929
def LoadDefaultEditor():
3030
pass
3131

32-
33-
## prefModule = GetDefaultEditorModuleName()
34-
## restorePrefModule = None
35-
## mod = None
36-
## if prefModule:
37-
## try:
38-
## mod = __import__(prefModule)
39-
## except 'xx':
40-
## msg = "Importing your preferred editor ('%s') failed.\n\nError %s: %s\n\nAn attempt will be made to load the default editor.\n\nWould you like this editor disabled in the future?" % (prefModule, sys.exc_info()[0], sys.exc_info()[1])
41-
## rc = win32ui.MessageBox(msg, "Error importing editor", win32con.MB_YESNO)
42-
## if rc == win32con.IDNO:
43-
## restorePrefModule = prefModule
44-
## WriteDefaultEditorModule("")
45-
## del rc
46-
##
47-
## try:
48-
## # Try and load the default one - don't catch errors here.
49-
## if mod is None:
50-
## prefModule = "pywin.framework.editor.color.coloreditor"
51-
## mod = __import__(prefModule)
52-
##
53-
## # Get at the real module.
54-
## mod = sys.modules[prefModule]
55-
##
56-
## # Do a "from mod import *"
57-
## globals().update(mod.__dict__)
58-
##
59-
## finally:
60-
## # Restore the users default editor if it failed and they requested not to disable it.
61-
## if restorePrefModule:
62-
## WriteDefaultEditorModule(restorePrefModule)
32+
# prefModule = GetDefaultEditorModuleName()
33+
# restorePrefModule = None
34+
# mod = None
35+
# if prefModule:
36+
# try:
37+
# mod = __import__(prefModule)
38+
# except Exception as error:
39+
# msg = (
40+
# f"Importing your preferred editor ('{prefModule}') failed."
41+
# + f"\n\nError {type(error)}: {error}"
42+
# + "\n\nAn attempt will be made to load the default editor."
43+
# + "\n\nWould you like this editor disabled in the future?"
44+
# )
45+
# rc = win32ui.MessageBox(msg, "Error importing editor", win32con.MB_YESNO)
46+
# if rc == win32con.IDNO:
47+
# restorePrefModule = prefModule
48+
# WriteDefaultEditorModule("")
49+
# del rc
50+
#
51+
# try:
52+
# # Try and load the default one - don't catch errors here.
53+
# if mod is None:
54+
# prefModule = "pywin.framework.editor.color.coloreditor"
55+
# mod = __import__(prefModule)
56+
#
57+
# # Get at the real module.
58+
# mod = sys.modules[prefModule]
59+
#
60+
# # Do a "from mod import *"
61+
# globals().update(mod.__dict__)
62+
#
63+
# finally:
64+
# # Restore the users default editor if it failed and they requested not to disable it.
65+
# if restorePrefModule:
66+
# WriteDefaultEditorModule(restorePrefModule)
6367

6468

6569
def GetEditorOption(option, defaultValue, min=None, max=None):

Pythonwin/pywin/framework/editor/vss.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@
1717

1818

1919
import os
20-
import sys
2120
import traceback
2221

2322
import win32api
@@ -96,9 +95,7 @@ def CheckoutFile(fileName):
9695
ok = 1
9796
except pythoncom.com_error as exc:
9897
win32ui.MessageBox(exc.strerror, "Error checking out file")
99-
except:
100-
typ, val, tb = sys.exc_info()
98+
except Exception as error:
10199
traceback.print_exc()
102-
win32ui.MessageBox(f"{typ} - {val}", "Error checking out file")
103-
tb = None # Cleanup a cycle
100+
win32ui.MessageBox(f"{type(error)} - {error}", "Error checking out file")
104101
return ok

Pythonwin/pywin/framework/intpydde.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
# is open. Strange, but true. If you have problems with this, close all Command Prompts!
66

77

8-
import sys
98
import traceback
109

1110
import win32ui
@@ -29,10 +28,9 @@ def Exec(self, data):
2928
# print("Executing", cmd)
3029
self.app.OnDDECommand(data)
3130
except:
32-
t, v, tb = sys.exc_info()
3331
# The DDE Execution failed.
3432
print("Error executing DDE command.")
35-
traceback.print_exception(t, v, tb)
33+
traceback.print_exc()
3634
return 0
3735

3836

Pythonwin/pywin/framework/scriptutils.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -603,7 +603,7 @@ def JumpToDocument(fileName, lineno=0, col=1, nChars=0, bScrollToTop=0):
603603

604604

605605
def _HandlePythonFailure(what, syntaxErrorPathName=None):
606-
typ, details, tb = sys.exc_info()
606+
details = sys.exc_info()[1]
607607
if isinstance(details, SyntaxError):
608608
try:
609609
msg, (fileName, line, col, text) = details
@@ -616,7 +616,6 @@ def _HandlePythonFailure(what, syntaxErrorPathName=None):
616616
else:
617617
traceback.print_exc()
618618
win32ui.SetStatusText(f"Failed to {what} - {details}")
619-
tb = None # Clean up a cycle.
620619

621620

622621
# Find the Python TabNanny in either the standard library or the Python Tools/Scripts directory.

0 commit comments

Comments
 (0)