Python – Exception handling

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:

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!”:

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

 

Tagged with: , , ,