Skip to content

Commit 9193d57

Browse files
committedOct 6, 2017
Added sample exceptions.
1 parent 7f0c574 commit 9193d57

File tree

1 file changed

+90
-0
lines changed

1 file changed

+90
-0
lines changed
 

‎sampleexceptions.py

+90
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
# python sampleexceptions.py
2+
3+
# Minimal types of exceptions are used in this sample.
4+
# For a list of built in python exceptions see https://docs.python.org/2/library/exceptions.html
5+
6+
7+
# Expected Output:
8+
#
9+
# Basic exception raised.
10+
# Basic exception with message: ERROR.
11+
# Caught non basic exception: No module named badimport.
12+
# Caught non basic exception: unsupported operand type(s) for +: 'int' and 'str'.
13+
# Demonstrated how to handle multiple types of exceptions the same way.
14+
# Demonstrated how to handle multiple types of exceptions the same way with a message: No module named badimport.
15+
# Demonstrated how to handle exceptions differently.
16+
# This should appear.
17+
# Demonstrated how finally is run after exceptions.
18+
# Demonstrated how else is run when no exceptions occur.
19+
# Demonstrated how to use a basic custom exception: Custom Exception.
20+
21+
22+
try:
23+
raise Exception
24+
except:
25+
print "Basic exception raised."
26+
27+
28+
try:
29+
raise Exception("ERROR")
30+
except Exception as e:
31+
print "Basic exception with message: %s." % str(e)
32+
33+
34+
try:
35+
import badimport
36+
except ImportError as e:
37+
print "Caught non basic exception: %s." % str(e)
38+
39+
40+
try:
41+
test = 1 + '1'
42+
except TypeError as e:
43+
print "Caught non basic exception: %s." % str(e)
44+
45+
46+
try:
47+
import badimport
48+
except ImportError, TypeError:
49+
print "Demonstrated how to handle multiple types of exceptions the same way."
50+
51+
52+
try:
53+
import badimport
54+
except (ImportError, TypeError) as e:
55+
print "Demonstrated how to handle multiple types of exceptions the same way with a message: %s." % str(e)
56+
57+
58+
try:
59+
import badimport
60+
except ImportError:
61+
print "Demonstrated how to handle exceptions differently."
62+
except TypeError:
63+
print "This should not appear."
64+
65+
66+
try:
67+
import badimport
68+
except ImportError:
69+
print "This should appear."
70+
finally:
71+
print "Demonstrated how finally is run after exceptions."
72+
73+
74+
try:
75+
test = 1 + 1
76+
except:
77+
print "This should not appear."
78+
else:
79+
print "Demonstrated how else is run when no exceptions occur."
80+
81+
82+
class CustomBasicError(Exception):
83+
""" Custom Exception Type - Can be customised further """
84+
pass
85+
86+
87+
try:
88+
raise CustomBasicError("Custom Exception")
89+
except CustomBasicError as e:
90+
print "Demonstrated how to use a basic custom exception: %s." % str(e)

0 commit comments

Comments
 (0)
Please sign in to comment.