Home » Learn Python » Exceptions » Exceptions Introduction

Exceptions Introduction

There are basically two different types of possible error in Python programs.

The first type, and often the most difficult to deal with, are errors in your logic. The program works but it doesn’t do what you expect. Your Python is perfectly legitimate and the computer does exactly what you tell it to do, but you’ve told it to do the wrong thing.

The second type of error is a syntax error. In this case, you haven’t written legitimate Python. With practice, these become very easy to fix.

If you try to run a Python program that contains syntax errors, you will see a traceback. This is a kind of error report that at first looks intimidating, but its entire purpose is to tell you where your program went wrong.

It’s possible to check for logic errors in your program and then “raise an error” or “raise an exception” if the logic is wrong. For example, if the value of a variable should be between 1 and 10, but it’s actually 11, you can raise an error automatically. This creates a traceback that informs you where the problem occurred and why.

Many Python libraries and builtin functions will raise an error, causing a traceback, under certain circumstances.

Raising an error is also called “throwing an exception“. The “error” or “exception” is “thrown” at some point it your code, and it can either be thrown all the way out of your program, causing a traceback, or it can be intercepted somewhere, or caught.

Here’s an example of a program that throws an exception and therefore produces a traceback.

value1 = 10
value2 = 0

Traceback (most recent call last):
  File "/Users/john/Documents/Python WordPress/./strings.py", line 4, in <module>
ZeroDivisionError: division by zero

You can see the traceback informs you on which line the error occurred, and why.

Leave a Reply

Blog at WordPress.com.