CodeGym /Java Course /Python SELF EN /Common Exceptions

Common Exceptions

Python SELF EN
Level 17 , Lesson 1
Available

2.1 Creating Exceptions

Can't beat 'em — join 'em. If we can't avoid errors in our program, we should learn to control them. So let's learn how to consciously create exceptions.

The simplest example of an exception is division by zero. And the program is simple too:


x = 100 / 0
        

This code will run with an error:


Traceback (most recent call last):
    File "", line 1, in 
         x = 100 / 0
        ~~~^~   
ZeroDivisionError: division by zero
        

ZeroDivisionError is the name of the exception, and division by zero is its short description. Python will also tell you the line number where this exception occurred.

Data Type Mismatch

Of course, other exceptions are possible. For example, trying to add a string and a number:


s = "100" + 100
        

A TypeError will occur:


Traceback (most recent call last):
    File "", line 1, in 
TypeError: unsupported operand type(s) for +: 'str' and 'int'
        

Out of Range in a List

Another very common error that generates an exception is trying to access an element that doesn't exist in a list:


my_list = [1, 2, 3]
print(my_list[10])
        

An IndexError will occur:


Traceback (most recent call last):
    print(my_list[10])
        ~~~~~~~^^^^
IndexError: list index out of range
        

So, how many are there in total? There are thousands of different types of exceptions. Moreover, you can create your own if the existing ones are not enough to describe some specific situation. Although the most popular ones aren't that many.

2.2 List of the Most Popular Exceptions

There are many exceptions, but as a newbie, it will be useful for you to know about the most popular ones. Below I will provide a table with them:

Exception Description
Exception The base class for all exceptions.
IndexError Occurs when trying to access an index that is out of range in a sequence (like a list or tuple).
KeyError Occurs when trying to access a non-existent key in a dictionary.
NameError Occurs when a variable that doesn't exist is accessed.
RuntimeError Occurs due to a general runtime error, not related to other types of exceptions.
StopIteration Occurs to signal the end of an iteration.
SyntaxError Occurs due to a syntax error in the code.
IndentationError Occurs due to incorrect indentation in the code (subtype of SyntaxError).
TabError Occurs when tabs and spaces are mixed for indentation (subtype of IndentationError).
TypeError Occurs when an operation is attempted between incompatible data types.
UnboundLocalError Occurs when a local variable is accessed before it is declared (subtype of NameError).
ValueError Occurs when a function or operation receives an argument of the correct type but inappropriate value.
ZeroDivisionError Occurs when division by zero is attempted.

Most likely, as a newbie, you'll encounter all these errors in your first month of study. And that's okay — you only learn from mistakes.

2.3 Errors in Code

Let's consider a few more situations when errors occur in code, so you can find them more easily in your own code:

IndentationError

This type of error occurs when the indentation in code is done incorrectly. For example, mixing tabs and spaces or incorrect amount of indentation.


def example():
    print("Hello")
     print("World")  # Incorrect indentation causes IndentationError
        
example()
        

NameError


def example():
    print(undeclared_variable)  # Attempt to use an undeclared variable causes NameError
        
example()
        

ValueError

This type of error occurs when an operation or function receives an argument of the right type but inappropriate value.


def example():
    int("abc")  # Attempt to convert a string that isn't a number causes ValueError
        
example()
        

KeyError

This type of error occurs when the program tries to access a non-existent key in a dictionary.


def example():
    my_dict = {"a": 1, "b": 2}
    print(my_dict["c"])  # Attempt to access a non-existent key causes KeyError
        
example()
        

SyntaxError

This type of error occurs due to a syntax error in the code, meaning the code doesn't match the Python grammar.


def example():
    eval("if True print('Hello')")  # Incorrect syntax causes SyntaxError
        
example()
        

Forewarned is forearmed. Now you can recognize and create situations that cause errors. It's time to learn how to handle these errors.

2
Task
Python SELF EN, level 17, lesson 1
Locked
Indentation Error.
Indentation Error.
2
Task
Python SELF EN, level 17, lesson 1
Locked
Syntax Error.
Syntax Error.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION