Table of Contents[Hide][Show]
This lecture is going to be important if you are dealing with large programs.
You will learn to handle the errors through exception blocks and using comments in Python.
Exceptions
We are going to learn how to handle errors in Python programs. Let’s start by writing a small program to get the user’s age from the terminal.
age = int(input('Age'))
print(age)
Let’s run it.
Now, look at the exit code of this program. Exit code 0 means our program terminated successfully and there were no errors. But what if we run this program one more time and instead of entering a numerical value, we enter a string?
We get a value error with his message “invalid literal for int() with base 10” Basically what this message is telling us is that this string “qwe” does not contain a valid home number that can be converted to an integer. Now, look at the exit code of this program. Exit code 1 means our exit code crashed, so 0 always means success and anything but 0 means crash. In programming, we refer to this kind of error as an exception.
As a good python programmer, you should anticipate this situation. You don’t want to let your entire program crash just because the user entered an invalid value. So instead of letting the program crash you should handle the situation and print a proper error message. That’s what I’m going to show you in this lecture.
In Python, we have a construct called try except
used to deal with error situations.
try:
age = int(input('Age'))
print(age)
These two lines of code are part of our try:
block. We will add except
block after it with the type of error we are anticipating.
except ValueError:
print('Invalid Value')
It will now return the string “Invalid Value” in case of a value error.
Let’s check another kind of error by altering the previous program.
try:
age = int(input('Age'))
income = 20000
risk = income / age
print(age)
except ValueError:
print('Invalid Value')
Now, if we run this program and input ‘0’ in age, a numerical value. Hence, technically, we should not get any exceptions.
Let’s run it.
Take a look. Our program crashed and we did a “Zero Division Error” because we cannot divide a number by 0. Once again look at the exit code. We couldn’t catch this kind of error or this kind of exception with this except block.
This except block is only catching exceptions of type value error and we will need a new except block to handle Zero Division Error. Let’s modify the program accordingly.
try:
age = int(input('Age'))
income = 20000
risk = income / age
print(age)
except ZeroDivisionError:
print('Age cannot be 0')
except ValueError:
print('Invalid Value')
The problem is solved!
- Syntax error
- Typeerror
- Nameerror
- Indexerror
- Valueerror
- Zerodivisionerror
- Attributeerror
- Runtime error
- Keyerror
- Memoryerror
- Assertionerror
- Indentationerror
- Eoferror
- Floatingpointerror
- Overflowerror
- Logic error
- Systemerror
- Notimplementederror
- Oserror
- Ioerror
- Referenceerror
- Unicodeerror
- Arithmeticerror
- Unicodedecodeerror
- Unicodeencodeerror
- Unicodetranslateerror
- Runtime Errors
As a programmer, you should be aware of all the exceptions in your program and you should handle them accordingly.
Comments
Now, we are going to talk about comments in python. We use comments to add notes or comments to our programs to improve readability and convey some message to someone reading our code.
Comments can be written in the program by using the # sign. Everything you write after the # will be ignored by the Python compiler and will not be executed. You can add comments on individual lines as well as after a line of code.
With these comments, we can explain something about our code, we can use them as reminders to fix things or clear things up, or we can use them to communicate things with other developers reading our code or to explain why we have written this code in a certain way. These are good use cases for using comments. we can also have comments over multiple lines. Each line should start with a new # sign. Now one thing you need to avoid when using comments is explaining what the code does.
Here is an example of a bad comment:
This is a bad comment because it’s telling me the obvious. It’s telling me that the next line is going to print “Sun sets in the West”. Now the problem with this comment is that apart from being verbose and repetitive if you come here and change West to East, this comment gets outdated. So, every time we update our code we will have to come back and modify the corresponding comment.
In short, use your comments to answer hows and why’s instead of what’s.
Here is an example of a good comment:
In the first comment, I am reminding myself that I need to update this income value before finalizing the program and the second value is telling other developers reading my code that all errors are not handled in this program.
Conclusively, you should avoid redundant comments and your comments should add some value to your code.
Wrap Up!
Exceptions and comments are two aspects of programming that are often overlooked and their significance is usually underrated.
Crashing your program is almost as bad as not commenting on your code where needed. The next lecture will focus on Classes and Constructors.
Leave a Reply