When writing a program, we, more often than not, will encounter errors.
Error caused by not following the proper structure (syntax) of the language is called syntax error or parsing error.
>>> if a < 3 File "<interactive input>", line 1 if a < 3 ^ SyntaxError: invalid syntax
We can notice here that a colon is missing in the if statement.
if
Errors can also occur at runtime and these are called exceptions. They occur, for example, when a file we try to open does not exist (FileNotFoundError), dividing a number by zero (ZeroDivisionError), module we try to import is not found (ImportError) etc.
FileNotFoundError
ZeroDivisionError
ImportError
Whenever these type of runtime error occur, Python creates an exception object. If not handled properly, it prints a traceback to that error along with some details about why that error occurred.
>>> 1 / 0 Traceback (most recent call last): File "<string>", line 301, in runcode File "<interactive input>", line 1, in <module> ZeroDivisionError: division by zero >>> open("imaginary.txt") Traceback (most recent call last): File "<string>", line 301, in runcode File "<interactive input>", line 1, in <module> FileNotFoundError: [Errno 2] No such file or directory: 'imaginary.txt'
Illegal operations can raise exceptions. There are plenty of built-in exceptions in Python that are raised when corresponding errors occur. We can view all the built-in exceptions using the local() built-in functions as follows.
local()
>>> locals()['__builtins__']
This will return us a dictionary of built-in exceptions, functions and attributes.
Some of the common built-in exceptions in Python programming along with the error that cause then are tabulated below.
assert
input()
close()
next()
sys.exit()
We can also define our own exception in Python (if required). Visit this page to learn more about user-defined exceptions.
We can handle these built-in and user-defined exceptions in Python using try, except and finally statements.