Exception handling#
The basics about exceptions#
Example#
1#!/usr/bin/env python3
2
3def main():
4 try:
5 print(x)
6 except:
7 print("An exception occurred")
8
9
10if __name__ == "__main__":
11 main()
Output#
1An exception occurred
Example#
1#!/usr/bin/env python3
2
3def main():
4 try:
5 print(x)
6 except SystemError:
7 pass
8
9
10if __name__ == "__main__":
11 main()
Output#
1Traceback (most recent call last):
2 File "/workspaces/learning-python/test1.py", line 11, in <module>
3 main()
4 File "/workspaces/learning-python/test1.py", line 5, in main
5 print(x)
6NameError: name 'x' is not defined
Example#
1#!/usr/bin/env python3
2
3def main():
4 x = 1
5 try:
6 print(x)
7 except:
8 print("System Error")
9 else:
10 print("Everything fine")
11
12
13if __name__ == "__main__":
14 main()
Output#
11
2Everything fine
Example#
1#!/usr/bin/env python3
2
3def main():
4 try:
5 print(x)
6 except:
7 print("System Error")
8 finally:
9 print("The try-except works")
10
11
12if __name__ == "__main__":
13 main()
Output#
1System Error
2The try-except works
Raise an exception#
Example#
1#!/usr/bin/env python3
2
3def main():
4 x = 1
5 y = 0
6
7 if y == 0:
8 raise Exception("Sorry, can not divide by zero")
9 else:
10 print(x/y)
11
12if __name__ == "__main__":
13 main()
Output#
1Traceback (most recent call last):
2 File "/workspaces/learning-python/test1.py", line 13, in <module>
3 main()
4 File "/workspaces/learning-python/test1.py", line 8, in main
5 raise Exception("Sorry, can not divide by zero")
6Exception: Sorry, can not divide by zero
Example#
1#!/usr/bin/env python3
2
3def main():
4 x = 1
5 y = "zero"
6
7 if not type(y) is int:
8 raise TypeError("Only integers are allowed")
9 else:
10 if y == 0:
11 raise Exception("Sorry, can not divide by zero")
12 else:
13 print(x/y)
14
15
16if __name__ == "__main__":
17 main()
Output#
1Traceback (most recent call last):
2 File "/workspaces/learning-python/test1.py", line 16, in <module>
3 main()
4 File "/workspaces/learning-python/test1.py", line 8, in main
5 raise TypeError("Only integers are allowed")
6TypeError: Only integers are allowed