Python - Exception Handling

Errors are unavoidable. As a developer, we always have to encounter multiple errors in the initial phase of development. And at the end of the development, the business logic/application which we developed should not misbehave or terminate due to some unexpected events during execution.

In General, Errors in python can be of two types

  • Syntax Errors/Compile Time Error - Syntax mistakes which result in termination of the program.
#syntax error example
a = 5
if(a)
print("Value present")

#result
File "main.py", line 2
    if(a)
        ^
SyntaxError: invalid syntax
  • Exception/Run Time Error - Abnormal execution of the program which result in error.
#Exception example
a = 5
b = 0

c = a/b
print(c)

#result
File "main.py", line 4, in module
    c = a/b
    
ZeroDivisionError: division by zero
Even though there is no syntax errors, it ended in ZeroDivisionError. This is due to, we are trying to divide a number by 0.

Exception Handling:
  • When an error or exception occurs, python will stop its execution and it also generate an error message.
  • In Python, we can handle the exceptions using try, except, finally blocks.
    • try block - Test a block of code for errors.
    • except block - Handles the error if any error thrown.
    • finally block - Exceutes some code, regardless of the try - except block result.
num_list = [1,2,"3",4]

try:
  for number in num_list:
      total+=number
  print(total)
  
except:
  print("Some error occured")
  
#result
Some error occured
In the above example, Inside the try block we are trying to add a string to number which results error and exception is thrown. This exception is captured by except block and statements inside the except block is exceuted.

Catching Specific Exception:
  • We have seen how to handle exception when its thrown. Now what if I want to handle exception based on exception type/different kind of errors.
  • This can be achieved by adding more except block with exception type for a try block. 
  • Whenever an exception is thrown from try block, it will check which except block is matching with the thrown exception message. If match found then respective except block statements will get exceuted.
  • If no match found, then default except (without exception message) block will get exceuted.
def calcAvg(num_list):
    try:
        if len(num_list) > 0: 
            total = 0
            for number in num_list:
              total+=number
        print(total)
      
    except NameError:
        print("NameError occured")
    
    except TypeError:
      print("TypeError occured")
        
    except:
        print("Some Error occured")
        
calcAvg([]) #NameError occured
calcAvg([1,2,"3",4]) #TypeError occured
Try with Else:
  • We can also define an else clause for a try-except block. And, the statements inside the else block will be executed only if there is no exception thrown by the try block.
  • Else block should always present after all the except block.
num_list = [1,2,3,4]

try:
    total = 0
    for number in num_list:
      total+=number
    print(total)

except TypeError:
    print("TypeError occured")
    
except:
    print("Some error occured")

else:
    print("No Error occured")
        
#result
10
No Error occured
Finally block:
  • Finally block code will always be executed regardless if the try block throws an exception or not.
  • In real life practice, this finally block is used to close database connections or close the file at the end of all operations Since its guarantees the execution.
f = open("demofile.txt")

try:
    f.write("Lorum Ipsum")
    
except:
    print("Something went wrong when writing to the file")
    
finally:
    f.close()
Raise an Exception:
  • We can also raise our own exception by using the raise keyword.
  • It has an option to specify what type of error to raise and also error message.
try:
    number = -1

    if number < 0:
      raise Exception("Negative Numbers not allowed")

except ValueError as e:
    print(e)

#result
File "main.py", line 6, in module
    raise Exception("Negative Numbers not allowed")
Exception: Negative Numbers not allowed

No comments:

Post a Comment

You might also like

Deploy your Django web app to Azure Web App using App Service - F1 free plan

In this post, we will look at how we can deploy our Django app using the Microsoft Azure app service - a free plan. You need an Azure accoun...