Exception handling in python is actually quite an interesting topic. In general, the exceptions in programming could be of three types:
- syntactic errors – these would be noticed by your IDE or by the interpretor, thus you do not need to handle those;
- logic errors – these are tough to find, as the program does not know what is in your head, while you are programming;
- run-time errors – these are easy to spot (as the program stops in runtime) and could be handled through exception handling;
The standard hadler looks like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import sys, traceback try: x = 5 / 0 except: Type, Value, Trace = sys.exc_info() print("Type: ", Type) print("Value:", Value) print("Trace:", Trace) traceback.print_exception(Type, Value, Trace, limit=10, file=sys.stdout) traceback.print_tb(Trace, limit=5, file=sys.stdout) print(traceback.format_exception(Type, Value, Trace, limit=10)) print(traceback.format_exception_only(Type, Value)) else: print("No error found!") finally: print("This code will be always printed!") |
And the message it produces is actually quite useful:
Custom error class
There is a way to make a custom error class and handle the error message from there. In the code below, there is a custom error, thrown because the variable i
is above 11
, with notice “Not supposed to increase variable i
aboive 10!”:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class MyError(Exception): def __init__(self, value): self.msg = value def __repr__(self): return self.msg def print_info(self): print(self) try: i = 11 if i > 10: raise MyError("Not supposed to increase variable 'i' above 10!") except MyError as err: err.print_info() |
Well, pretty much this is all I wanted to write. In general, it is good to explicitly state which exception is going to be handled by the code, using the various types of exceptions in Python – https://docs.python.org/3/library/exceptions.html