The try and except statements in python helps us to mitigate exception errors with a meaning full way. To understand why we require try and except statements we should know how python handles execution and syntax errors.
There are two types of errors in Python
1)Syntax errors 2)Exception errors
Syntax errors occur when there is a wrong syntax in your code and where as exception errors occur when executing the code and found something wrong with file permissions, floating point error, division by zero error, IO errors, Name errors etc though the syntax of the code is right one.
Try and except statements are useful in countering these exception errors. When ever your code come across these exceptions, your try and exception statements help in changing the behavior of your program in a meaning full way.
Let us learn try and except statements with examples
Try and Except statement syntax:
try: do something here except exception-code: do something if found exception-code error
Example 1: Open a file and secure the error with IOError exception if file do not exit’s
#!/usr/bin/python try: f = open('abci.txt', 'r') except IOError: print "Can not open the file"
Example 2: Ok, that is fine how about if you try to give illegal mode to open a file like ‘d’ mode? We have to counter this with multiple exceptions which may occur
#!/usr/bin/python try: f = open('abc.txt', 'dsf') print "Sucessfully opened the file" except IOError: print "Can not open the file because due to file open issues " except ValueError: print "Can not open the file because some another thing happen"
Example 3: Clubbing multiple exception to form compound statement
#!/usr/bin/python try: f = open('abc.txt', 'd') print "Sucessfully opened the file" except IOError and ValueError: print "Can not open the file because due to file open issues "
Example 4: Printing actual exception in output so that user will come to know what kind of error he is getting.
#!/usr/bin/python try: f = open('abc.txt', 'dsf') print "Successfully opened the file" except IOError as error1: print "Can not open the file because I got ", error1
Example 5: Printing actual trace back with exception in output so that user will come to know what kind of error he is getting by using raise statement.
#!/usr/bin/python try: f = open('abc.txt', 'r') print "Successfully opened the file" except IOError: print "Can not open the file because due to file open issues with below trace back" raise
Example 6: How about executing remaining code if there is no exception occur? Try and except can be combined with else statement so that if exception did not occur else block code is executed
#!/usr/bin/python try: f = open('abc.txt', 'r') print "Sucessfully opened the file" except IOError: print "Can not open the file because due to file open issues " else: print "I am in else loop" f.close()
Example 7: How about executing some code once this try-except loop is executed and want to execute this code irrespective of exception occur or not. To do this we have to use finally statement to execute this code.
#!/usr/bin/python try: f = open('abc.txt', 'r') print "Successfully opened the file" except IOError: print "Can not open the file because due to file open issues " else: print "I am in else loop" f.close() finally: print "This is the code finally>executed for this try example"
We should know below key words to understand try and exception statements
try: --Will try to execute code which may contain exception except: --Once this exception occur and matches the exception which we are looking, then the code in this exception block is executed. raise: --Nothing but actual trace back with complete error message finally: --The code which we want to execute finally once try and except/else blocks are executed. This is equal to END block in Perl and AWK. else: --If no exception occur execute the code in this block.
Latest posts by Surendra Anne (see all)
- Docker: How to copy files to/from docker container - June 30, 2020
- Anisble: ERROR! unexpected parameter type in action:
Fix - June 29, 2020 - FREE: JOIN OUR DEVOPS TELEGRAM GROUPS - August 2, 2019
- Review: Whizlabs Practice Tests for AWS Certified Solutions Architect Professional (CSAP) - August 27, 2018
- How to use ohai/chef-shell to get node attributes - July 19, 2018