You are the only Exception

--Originally published at Programming

Introduction to Exceptions

It’s been a long journey for some of you. Whether you’ve spent 10+ hours coding or just a couple, I’m pretty sure you are familiar with the error messages that the console displays when your code is wrong. So far you don’t care if the user enters a number when they are supposed to enter a string, but that’s from the past. It’s now time for us to take the next step and start handling exceptions. By now you should know that there are at least two important noticeable kinds of errors: syntax errors and exceptions.

Syntax Errors

Probably one of the most common kind of errors for the people that are still in the process of learning Python. The console will print a Syntax Error message showing you with an arrow ^ the earliest point in the line where the error was detected, followed by the number of the line so you know where to look.
1.png

2.png

Exceptions

A statement or an expression can be syntactically correct and yet, an error may occur when the program is executed. This is caused because of an exception, which is defined as an error occurred during the execution of a program. Exceptions come in different types, some types for the exceptions are:

  • ZeroDivisionError (Divide a number by 0)
  • TypeError(When an operation or function is applied to an object of inappropriate type)
  • ImportError(When an import statement fails to find the module)
  • IndexError(When a sequence substring is out of range)
  • KeyError(When a Dictionary key is not found in the set of existing keys)
  • ValueError()

Check out the documentation for the Python 3.5 Built-in Exceptions here

Handling Exceptions

Now that we know some types of exceptions, it’s time for us to learn how to handle them. Let’s take a look at the following example where the program asks

3.png
5.png
6.png
Continue reading "You are the only Exception"