In Python there are three main types of exceptions/errors that a programmer has to deal with. There are different ways to handle each one according to their types, but first let's go through them.
SyntaxError
/IndentationError
and also indicates the line causing the error when found. SyntaxError
is raised due to a syntactical error in code such as missing colon in compound statements, invalid condition checking in if
...else
statements, missing string quote or bracket operator's termination, empty import
statement, missing/misspelling keywords, empty function/class definition etc. IndentationError
is raised when using a invalid indentation in compound statements.## SyntaxError
## Example 1: Missing closing brackets in list and
# missing inverted comma in a string
data = [232,54,65 # SyntaxError
data = "this string is not complete # SyntaxError
## Example 2: Missing colon in function
def myfun() # SyntaxError
print("my function")
## IndentationError
## Example 1: Wrong indentation in condition
a = 30
if a == 30:
print("Execute this") # Execute this
print("This will raise a Indentation error") # IndentationError
Some common runtime errors in Python.
AttributeError
: Raised when an attribute reference or assignment fails.TypeError
: Raised when an operation or a function is applied to an object of inappropriate type.ValueError
: Raised when an operation or a function receives an argument that has the right type but an inappropriate value.RecursionError
: Raised when the maximum recursion depth is exceeded, also called StackOverFlow error.IndexError
: Raised when a sequence subscript is out of range.KeyError
: Raised when a mapping (dictionary) key is not found in the set of existing keys.Exception
class and unlike all other exceptions they don't terminate the program. They are only meant to warn the user by showing some message.## Example 1: IndexError: Indexing error
a = [34, 56, 32, 87]
print(a[6]) # IndexError
## Example 2: ZeroDivisionError: Dividing by zero
print(34 / 0) # ZeroDivisionError
## Example 3: AttributeError: Accessing unknown attribute
import math
math.square # AttributeError
## Example 4: Raise a warning
import warnings
warnings.warn("Something is not right.") # UserWarning: Something \
# is not right.
print("This can execute") # This can execute
## Example 1: Accessing wrong index
my_list = [82, 92, 38, 42, 54, 23, 64, 87]
# printing last 3 values
print(my_list[-2:]) # [64, 87]
# here our program has no error, but instead of printing 3 numbers
# it's only printing 2 numbers, because we provided wrong index
# this example is not hard to fix, but in larger programs it might consume some
# time to find out which object/variable/function has caused the wrong output