Error and Exception in Python

Python often produces exceptions when an error occurs during execution. Quantum will work with you to learn about the different exceptions built into this language.

Python often produces exceptions when an error occurs during execution. Quantum will work with you to learn about the different exceptions built into this language. Invites you to read the track.

Error (Error)

When writing a program, frequent errors are inevitable.

There are some errors that do not follow the correct structure of the syntax causing syntax errors ( syntax error or parsing error ).

 >>> if a < 3 
File "", line 1
if a < 3
^
SyntaxError: invalid syntax

The above command is missing a colon in the IF statement immediately, the syntax of the invalid syntax program .

Exception (Exception)

In addition, there is a Python case that generates an error while executing the program ( runtime error ). These errors are called exceptions.

Exceptions are created by Python to handle that problem to prevent the program from crashing.

Some examples of Exception are:

  1. Open a non-existent file (FileNotFoundError)
  2. Divide a number by 0 (ZeroDivisionError)
  3. The module imported (ImportError) was not found .
  4. Pass the value into a function with the correct type but the value is not appropriate (ValueError).

Whenever a runtime error occurs, Python will create an exception object.

If it is not handled correctly, the program will print an error and details the reason for the error.

 >>> 1 / 0 
Traceback (most recent call last):
File "", line 301, in runcode
File "", line 1, in
ZeroDivisionError: division by zero

>>> open("imaginary.txt")
Traceback (most recent call last):
File "", line 301, in runcode
File "", line 1, in
FileNotFoundError: [Errno 2] No such file or directory: 'imaginary.txt'

Exceptions are created by Python

There are many exceptions created by Python when encountering the corresponding errors.

You can see all available Exception cases using the local () function as follows:

 locals()['__builtins__'] 

This function will return a list of Python built-in exceptions, functions and attributes.

Quantrimang would like to introduce some built-in exceptions in Python along with the error causing it in the table below:

Exception Reason for AssertionError Occurs when assert statement fails. AttributeError Occurs when assigning attributes or references failed. EOFError Occurs when the input () function touches the end-of-file condition. FloatingPointError Occurs when a floating-point implementation fails. GeneratorExit Occurs when the close () method of the generator function is called. ImportError Occurs when an imported module is not found. IndexError Occurs when a sequence index is out of range. KeyError Occurs when a mapping key (dictionary) cannot be found in the set of existing keys. KeyboardInterrupt Occurs when the user presses the interrupt key (usually Ctrl-C or Delete). MemoryError Occurs when an operation runs out of memory but the situation can still be corrected (by deleting some objects). NameError Occurs when a local or global name of the variable cannot be found. NotImplementedError Occurs in abstract methods when they require derived classes to override the method. OSError Occurs when a function returns an error related to the OverflowError system Occurs when the result of an arithmetic operation is too large to be represented. ReferenceError Occurs when a weak reference proxy is used to access a reference property after garbage collection. RuntimeError Occurs when an error does not belong to any other category. StopIteration Occurs with the next () method of a loop to signal that no value is returned by the iterator. SyntaxError Occurs when a syntax error is encountered. IndentationError Occurs when an indentation error is incorrect. TabError Occurs when indentation uses inconsistent tabs and spaces. SystemError Occurs when the interpreter finds internal errors but the situation is not too serious. SystemExit Occurred by the sys.exit () function. TypeError Occurs when a function or operation executes an incorrect type for an object. UnboundLocalError Occurs when the reference constitutes a local variable in a function or method, but no value is bound to that variable. UnicodeError Occurs when a Unicode UnicodeEncodeError related error occurs when a Unicode-related error occurs during the encryption process. UnicodeDecodeError Occurs when a Unicode-related error occurs during the decoding process. UnicodeTranslateError Occurs when Unicode-related errors are in translation. ValueError Occurs when an operation or function receives an argument of the correct type but the ZeroDivisionError non-conforming value Occurs when the second argument of division or modulo operation is 0.

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

In addition, you can define your exception in Python if necessary.

These two issues will be guided by Quantrimang in subsequent articles. Please follow us.

See more:

  1. Working with File in Python
  2. Matrix in Python
  3. Code Python on the browser with free online Python interpreters

Previous article: Managing files and folders on Python

Next article: Exception handling - Exception Handling in Python

4 ★ | 1 Vote