Error Types in Python

In this tutorial, we are going to discuss the types of errors, explanations, and examples in Python.

Errors and it’s explanation

Errors in Python can be mainly divided into two categories

  1. Syntax error
  2. RuntimeError

SyntaxError

The syntax can be called as compile-time errors. This is the most common error in Python. The error happens before compiling the code. If the code cannot be compiled successfully then the error happens. We all know that the source code is compiled into machine-level language (that is 0 and 1) if the conversion cannot be performed then this error is called a compile-time error. The conversion cannot be performed because the error in syntax that means the error in the structure of code. For example, you are performing a while or a for loop you forget to give the colon, or performing a print statement but you have not given the brackets then this type of error happens.

Example:

>>>for i in range(1,10)
             print (i)

SyntaxError: invalid syntax

 

RuntimeError

The run time error happens when the syntax run successfully but there are some mistakes in the code or some logical mistakes in the code that’s why there happens a RuntimeError. It causes the program to crash unexpectedly or Suddenly. There are many types of runtime errors also;

  • IndexError
  • ModuleNotFoundError
  • KeyError
  • ZeroDivisionError
  • NameError
  • StopIteration
  • TypeError
  • ValueError
  • ImportError

 

For example: If you are going to divide an integer number by 0. Then these types of error occur. Clearly there is no error in syntax but there is an error in the logic that’s why the program cannot be performed. So the error is called as RuntimeError

 >>>print(45/0)
Traceback (most recent call last):
      File "<pyshell#2>", line 1, in <module>
            print(45/0)
ZeroDivisionError: division by zero

Leave a Reply

Your email address will not be published.