Python Exceptions

In this tutorial, you will learn about the different types of errors and built-in exceptions in Python. These exceptions are raised when the Python interpreter finds an error.

In programming, there are basically two types of errors:

  • Syntax Errors
  • Logical Errors (Exceptions)

Python Syntax Errors

While programming, you can make mistakes like using the wrong keyword, not indenting the code correctly, missing a symbol, etc. These types of errors are called syntax errors.

Here's an example:

a=5
b=6
print(a+b)

When you run the above code, the interpreter will give you an error:

Traceback (most recent call last):
File "<string>", line 3, in <module>
NameError: name 'prin' is not defined

Syntax Errors can be fixed by simply debugging the code and fixing any typos and mistakes. In our case, we just need to replace prin with print to fix the error.


Python Logical Errors (or Exceptions)

Consider the following program:

numerator = 10
denominator = 0
print(numerator/denominator)

The program above is syntactically correct yet it produces the following error:

Traceback (most recent call last):
File "<string>", line 4, in <module>
ZeroDivisionError: division by zero

These types of logical errors are called exceptions. Even though the code is syntax wise, we cannot logically divide any number by zero. So, it raises a ZeroDivisionError exception.


Python Built-In Exceptions

Many Python built-in exceptions are raised in case of certain logical errors in the code. We have provided a few of these exceptions in the table below:

Exception Cause
SyntaxError When a syntax error is encountered.
IndentationError When there is incorrect indentation.
MemoryError When an operation runs out of memory.
TypeError When a function or operation is applied to an object of the incorrect type.
OverflowError When the result of an arithmetic operation is too large to be represented.
FileNotFoundError When you are trying to operate on a file that doesn't exist.
ImportError When you are trying to import a non-existent module.
OSError. When system operation causes a system-related error.
RuntimeError When an error does not fall under any other category.

Handling Exceptions

Whenever there is an exception, Python code stops interpreting and displays an error message. As a programmer, you'd want a user to see a custom message rather than the default one. This is known as exception handling

With Python, we can also create user-defined exceptions to raise exceptions when users do something that we don't want them to do.

To handle exceptions, we can use the try, except, and finally statements.

Visit our Python Exception Handling tutorial for more information.

Did you find this article helpful?