-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path21_exceptionsExample.py
More file actions
executable file
·40 lines (31 loc) · 1.13 KB
/
21_exceptionsExample.py
File metadata and controls
executable file
·40 lines (31 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#!/usr/bin/env python3
"""
Exceptions in Python
How to deal with errors / exceptions like "File not found", "division by zero",
"conversion not possible" etc. in Python and prevent that your program crashes
for example by wrong formatted input files etc.
https://wiki.python.org/moin/HandlingExceptions
Jens Dede, 2019, jd@comnets.uni-bremen.de
"""
print(5*"*", "Catch a specific error")
try:
print(1/0) # Division by zero not possible -> Exception
except ZeroDivisionError: # Will catch the ZeroDivisionErrors
print("Division by Zero catched")
# Do whatever is necessary to solve the exception
print(5*"*", "Catch a general error")
try:
print(2/0) # Again an exception
except:
print("Something went wrong...")
print(5*"*", "Catch a general error with some more information")
try:
print(3/0) # Again an exception
except Exception as e:
print("Something went wrong and I have the following information:")
print(e)
# The following line will show what happens if an error is not caught:
# Program will crash...
a = 5/"b"
# ... and the following print will never be executed
print("You will never see this message")