Exception are unintended errors in the program. When an error occurs your program stops, however, we might want to handle these exception and continue the flow of execution of your program. When should you perform exception handling ? Generally, when you take user inputs or, your program depends on other resources like files, hard disk memory, third party API, etc. exception handling is performed. Exception handling in python is performed using try except block.
Try except can be used with finally, and else block. Let’s define these terminologies
try – you put what you want to test for error.
except– executes when there is error in the try block
finally– executes regardless there is error or not in the try block. This will always execute after try
else– execute when there is no error in the try block. It does not execute when there is an error.
Syntax for try except.
try: # testing statement except <ExceptionName>: # handling exception finally: # finally block this block is optional else: # else block code this is also optional
Let’s see an example of divide by zero error handling
try: result = 50/ 0 except: print('divide by zero')
divide by zero
Multiple exception block:
You can put multiple exception block to handle various errors. Let’s see an example
user_inputs = ['t', 0] # let's do a divide function for item in user_inputs: try: tax = 50000 / item except TypeError: print('Value error ') except ZeroDivisionError: print('Divide by zero ') except Exception: print('Other exception')
Value error Divide by zero
You can also print the exception raise by the system rather than printing your own error message. To do that you have to use as keyword and place a variable and print the variable.
Let’s see above example by printing system generated message.
user_inputs = ['t', 0] # let's do a divide function for item in user_inputs: try: tax = 50000 / item except TypeError as t: print(t) except ZeroDivisionError as z: print(z) except Exception as e: print(e)
unsupported operand type(s) for /: 'int' and 'str' division by zero
Raising an exception
Sometimes you want to stop the execution of the program if any error occurs so that it does not lead to further more error. Raising an error is nice way of letting client know there is an error and the program will stop now. You use a raise keyword to perform this action. Let’s see an example
user_age = 13 if user_age < 18: raise Exception('Age must be 18 or more to use our system') print("Age check complete")
Traceback (most recent call last): File "/home/PythonCourseCreation/20_tryexcept.py", line 49, in <module> raise Exception('Age must be 18 or more to use our system') Exception: Age must be 18 or more to use our system
As you can see once the exception is raised the program stops and it does not go further. There for in this case the statement ‘Age check complete’ is not printed on the screen.
Finally and else block
The finally block is always executed, however the else block is only executed if there is no error in the system.
Let’s see an example without any error:
try: tax = 50000 / 10 except Exception as e: print(e) else: print('Else block') finally: print('Finally block !')
Else block Finally block !
You have to put else block always after except block and not after finally. Putting it after finally will result in invalid syntax.
Let’s see another example with exception in it.
try: tax = 50000 / 0 except Exception as e: print(e) else: print('Else block') finally: print('Finally block !')
division by zero Finally block !
As you can see there is divide by zero exception and finally block is also executed. Since there is an error else block is not executed.
When should you use else or finally?
Finally block is used when you have to perform clean-up after a certain action is performed in try. One example would be closing a database connection when the operation on database is completed in the try block. The else block is also used for clean-up when there is no exception. For instance, reading a file only when opening a file in reading mode is successful.