exception handling in Python


Just like any other languages, there are two types of errors you might have seen: syntax error and exceptions. Let’s discuss in detail about handling exceptions in python.

Overview

  • Syntax error: Occur when the syntax is wrong, in this case, your script code will not run completely due to errors in syntax like you might have forgotten braces or indentation issue, etc.
  • Exceptions: Occur when certain condition causes code to fail. Like if you are trying to open a file which does not exist if you try to get a value for a key in a dictionary which does not exist.
  • Exception handling is very important to handle situations which can cause your code to break. You might have to catch exceptions to avoid code to crash and it helps in logging/debugging.
  • In python exception handling can be done using try and except blocks.
  • In python you can use raise an exception (or manually throw an exception).
  • In python you can assert clause to test a condition and throw an exception if condition fails

 


syntax error examples:

>>> for x in range(1,5):
... print (x)
  File "<stdin>", line 2
    print (x)
        ^
IndentationError: expected an indented block
>>> print (5]
  File "<stdin>", line 1
    print (5]
            ^
SyntaxError: invalid syntax

 


Some common exceptions:

KeyError

>>> x={'a':1,'b':2}
>>> x["a"]
1
>>> x["c"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'c'
>>> 

NameError

>>> import re
>>> x="AAAA"
>>> x=re.sub("D","F",xx)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'xx' is not defined

TypeError

>>> x="a"
>>> x+5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
>>> 

ImportError

>>> import xyz
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named xyz

 


Except handling:

try:
 code...
 code...
 code...
 ## if any of the above code breaks it will goto except staements...

except (TypeError):
 #if above code generates TypeError below statements will be run
 print ("TypeError...  trying to add string (like "5") to number...."
 #handle exception code, maybe convert string to number etc..

except (x):
 #if above code generaes an exception (x) below code will be run
 #handle exception for x

except:
 ## if uncaught exception is generated below code will be run...
 print ("Uncaught exception")
 pass

finally:
 print ("Doing cleanup work")
 ## this section will always run

 


Exception Hierarchy

All exceptions inherit from the BaseException class. Below is the hierarchy.

BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception
      +-- StopIteration
      +-- StopAsyncIteration
      +-- ArithmeticError
      |    +-- FloatingPointError
      |    +-- OverflowError
      |    +-- ZeroDivisionError
      +-- AssertionError
      +-- AttributeError
      +-- BufferError
      +-- EOFError
      +-- ImportError
      |    +-- ModuleNotFoundError
      +-- LookupError
      |    +-- IndexError
      |    +-- KeyError
      +-- MemoryError
      +-- NameError
      |    +-- UnboundLocalError
      +-- OSError
      |    +-- BlockingIOError
      |    +-- ChildProcessError
      |    +-- ConnectionError
      |    |    +-- BrokenPipeError
      |    |    +-- ConnectionAbortedError
      |    |    +-- ConnectionRefusedError
      |    |    +-- ConnectionResetError
      |    +-- FileExistsError
      |    +-- FileNotFoundError
      |    +-- InterruptedError
      |    +-- IsADirectoryError
      |    +-- NotADirectoryError
      |    +-- PermissionError
      |    +-- ProcessLookupError
      |    +-- TimeoutError
      +-- ReferenceError
      +-- RuntimeError
      |    +-- NotImplementedError
      |    +-- RecursionError
      +-- SyntaxError
      |    +-- IndentationError
      |         +-- TabError
      +-- SystemError
      +-- TypeError
      +-- ValueError
      |    +-- UnicodeError
      |         +-- UnicodeDecodeError
      |         +-- UnicodeEncodeError
      |         +-- UnicodeTranslateError
      +-- Warning
           +-- DeprecationWarning
           +-- PendingDeprecationWarning
           +-- RuntimeWarning
           +-- SyntaxWarning
           +-- UserWarning
           +-- FutureWarning
           +-- ImportWarning
           +-- UnicodeWarning
           +-- BytesWarning
           +-- ResourceWarning

source: https://docs.python.org/3/library/exceptions.html

 


raising an exception

if you want to throw an error (raise exception) based on your logic/condition in program then you can use raise.

#!/usr/bin/python3

class error_custom(Exception):
 pass

name=input("Enter Name: ")
try:
 if name=="":
  raise error_custom
except error_custom:
  print ("Got custom error")
finally:
  print(f"You entered {name}")
#### running the program
$ ./py
Enter Name: bitarray
You entered bitarray

$ ./py
Enter Name: 
Got custom error
You entered 

 

+ There are no comments

Add yours