Errors and Exceptions in Python
Last Updated :
22 Oct, 2021
Errors are the problems in a program due to which the program will stop the execution. On the other hand, exceptions are raised when some internal events occur which changes the normal flow of the program.
Two types of Error occurs in python.
- Syntax errors
- Logical errors (Exceptions)
Syntax errors
When the proper syntax of the language is not followed then a syntax error is thrown.
Example
Python3
amount = 10000
if (amount> 2999 )
print ( "You are eligible to purchase Dsa Self Paced" )
|
Output:
It returns a syntax error message because after the if statement a colon: is missing. We can fix this by writing the correct syntax.
logical errors(Exception)
When in the runtime an error that occurs after passing the syntax test is called exception or logical type. For example, when we divide any number by zero then the ZeroDivisionError exception is raised, or when we import a module that does not exist then ImportError is raised.
Example 1:
Python3
marks = 10000
a = marks / 0
print (a)
|
Output:
In the above example the ZeroDivisionError as we are trying to divide a number by 0.
Example 2: When indentation is not correct.
Output:
Some of the common built-in exceptions are other than above mention exceptions are:
Exception |
Description |
IndexError |
When the wrong index of a list is retrieved. |
AssertionError |
It occurs when the assert statement fails |
AttributeError |
It occurs when an attribute assignment is failed. |
ImportError |
It occurs when an imported module is not found. |
KeyError |
It occurs when the key of the dictionary is not found. |
NameError |
It occurs when the variable is not defined. |
MemoryError |
It occurs when a program runs out of memory. |
TypeError |
It occurs when a function and operation are applied in an incorrect type. |
Note: For more information, refer to Built-in Exceptions in Python
Error Handling
When an error and an exception are raised then we handle that with the help of the Handling method.
- Handling Exceptions with Try/Except/Finally
We can handle errors by the Try/Except/Finally method. we write unsafe code in the try, fall back code in except and final code in finally block.
Example
Python3
try :
print ( "code start" )
print ( 1 / 0 )
except :
print ( "an error occurs" )
finally :
print ( "GeeksForGeeks" )
|
code start
an error occurs
GeeksForGeeks
-
- Raising exceptions for a predefined condition
When we want to code for the limitation of certain conditions then we can raise an exception.
Example
Python3
try :
amount = 1999
if amount < 2999 :
raise ValueError( "please add money in your account" )
else :
print ( "You are eligible to purchase DSA Self Paced course" )
except ValueError as e:
print (e)
|
please add money in your account
Please Login to comment...