Exception Handling in Python(2)

Migo
2 min readMay 6, 2021

Python provides a different class for each potential error. The following is its format.

try:
<Code that may cause an error>
except "type_of_error", as error_variable , :
<Code that will follow when errors occur>

else:
<Code that will be executed when there is no Error>
finally:
<Code that is to be executed regardless of error>

Example

try :
print('Before a possible error')
r = 10/0
print("but it's okay")#this will not be executed
except ZeroDivisionError: #pvm calls class and its instance
print("0으로 나누는 건 안돼요!!")
else:
print(" else")
finally:
print(2222)
print("==main=====")

Example of user Exception Class

Python users can create their own Exception class through inheritance. Basically, ABC(abstract basic class) for Exception is “BaseException”, so you may think “Okay it is way to go.”

However, look at this short description below.

class BaseException(object)
| Common base class for all exceptions
|
| Built-in subclasses:
| Exception
| GeneratorExit
| KeyboardInterrupt
| SystemExit

Although it is true that BaseException is the very base class for all exceptions, as it contains rather heavy subclasses like KeyboardInterrupt and SystemExit, It is recommended to inherit just “Exception” class.

The following is a toy example.

class MyException(Exception):
def __init__(self,value):
self.value = value
def __str__(self):
return self.value


def raise_exception(err_mgs):
raise MyException(err_mgs) #Creating object. At this point, program should be interrupted.

if __name__ == '__main__':
try:
raise_exception("My Error!!!")
# raise MyException("My Error!!!")
except MyException as e:
print(e)
print(sys.exc_info())
print(e.args)
e.with_traceback('My Error!!!')

For some of you who may not have been familiar with exception, this is the flow.

Firstly, the computer starts reading below ‘if __name__ == ‘__main__’:
: this is an entry point of a program.

Secondly, it reaches raise_exception() function with its argument(“My Error!!!”), calling that function on the stack memory.

Inside the function, it is met with ‘raise.’ A short description of ‘raise’ is as follows.

raise_stmt ::= "raise" [expression ["from" expression]]If no expressions are present, "raise" re-raises the last exception
that was active in the current scope. If no exception is active in
the current scope, a "RuntimeError" exception is raised indicating
that this is an error.
Otherwise, "raise" evaluates the first expression as the exception
object. It must be either a subclass or an instance of
"BaseException". If it is a class, the exception instance will be
obtained when needed by instantiating the class with no arguments.

As you can see, whether or not there is a current exception, ‘raise’ raises an error with the exception instance which is in this case, the instance of ‘MyException’.

With that error occurrence and instance, you go into ‘except’ and the rest of the codes are to give you a picture of what kinds of information which user class exception has.

--

--

Migo

Establishment Challenger. Love to put groundless assumption, not always though.