How Can We Help?
What is Error in Python?
A small typo mistake can direct to an error in any programming language because we have to follow the syntax rules while coding in any programming language.
In python, a syntax error is the most common error like if we print “Welcome Python” in python version 3 and write a code as below input code, it will give a SyntaxError.
Example (1)
print "Welcome Python"
Output:
SyntaxError: Missing parentheses in call to ‘print’
Similarly, if we forget to give a colon(:) in the definition of function/class/if-else etc., it will give a syntax error as below.
Example (2)
if a==0
Output:
SyntaxError: invalid syntax
We can resolve these kinds of syntax errors by writing proper/ missing syntax in our code.
What is Python Exception?
An exception is an error caused by a malfunctioning (like missing positional arguments, missing all arguments when calling methods, forgetting to import modules, etc.) of the code during execution. Or in other words, Exceptions are unexpected errors that can occur during the code execution.
In this, code might not have any syntax error, but it can direct to exceptions when it is executed. Whenever an exception occurs in the program, a program halts the execution, or we can say other code will not execute.
Python shows a very detailed exception message to understand the origin point and reason for the exception so that it becomes easier for anyone to fix the code.
For example, after executing the below input code, we got an error as TypeError.
Example (3)
>>> def add(a,b):
c=a+b
print("Sum value: ",c)
>>> add()
Output:
In the above output, Traceback means that python has traced the code back to the point where the exception occurred and will show the related messages after this line.
The second line in the output is the name of the python file and the exact line number for the code at which the exception was generated.
If that is still not helpful, then in the third line of output, the complete code statement is given, at which the error occurred.
And then, in the last line, python tells us which exception occurred, like TypeError in the above example.
Python In-built Exceptions
Python supports following built-in exceptions, which occur according to conditions, use of library files, and writing syntax. These are all defined as python classes, so we call them exception classes.
Exception Name | Description |
---|---|
ZeroDivisionError | It occurs when a number is divided by zero. |
Exception | It is a base class for all exceptions. |
StopIteration | It is raised when the next() method of an iterator does not point to any object. |
SystemExit | It is raised by the sys.exit() function. |
StandardError | It is a base class for all built-in exceptions except StopIteration and SystemExit. |
ArithmeticError | It is a base class for all errors that occur for numeric calculation. |
OverflowError | It is raised when a calculation exceeds the maximum limit for a numeric type. |
FloatingPointError | It is raised when a floating point calculation fails. |
AssertionError | It is raised in case of failure of the assert statement. |
AttributeError | It is raised when the attribute we are trying to access(whether for assigning a value or getting a value) doesn’t exist, like trying to access a class member variable that is not defined in the class. |
EOFError | If there is no input from either the raw_input() or input() functions, the EOFError is raised. This means operations are being performed, and the end of the file is reached. |
ImportError | It is raised when an imported module is not found. |
KeyboardInterrupt | It is raised when the user interrupts program execution. (like pressing Ctrl+c) |
LookupError | It is a base class for all lookup errors. |
IndexError | It is raised when an index is not found in a sequence. |
KeyError | It is raised when the specified key is not found in the dictionary. |
NameError | It is raised when a variable name is not found in the local/global namespace, or we can say the used variable name is not defined. |
UnboundLocalError | It is raised when accessing a local variable in a function or method, but no value has been assigned to it. |
EnvironmentError | It is a base class for all exceptions that occur outside the Python environment. |
IOError | It is raised when an input/ output operation fails, like a print statement or the open() function, when trying to open a file that does not exist. |
OSError | It is raised for operating system-related errors. |
SyntaxError | It is raised when there is an error in Python syntax. |
IndentationError | It is raised when indentation is not specified correctly. |
SystemError | It is raised when the interpreter finds an internal problem, but the Python interpreter does not exist when this error is encountered. |
SystemExit | It is raised when the Python interpreter is quit using the sys.exit() function. It exits the interpreter if we do not handle it in the code. |
TypeError | It is raised when an operation or function is executed on a variable of invalid data type. |
ValueError | It is raised when the built-in function for a data type has a correct type of argument, but the arguments have incorrect values. |
RuntimeError | It is raised when a generated error does not fall into the python-defined exception type category. |
NotImplementedError | It is raised when an abstract method that needs to be implemented in an inherited class is not implemented. |
TabError | When the indentation is inconsistent throughout the code regarding tabs and spaces used for indentation, the TabError error is raised. |
For Eg. Let’s create a “ZeroDivisionError” error.
Example (4)
>>> x=4
>>> y=0
>>> print("Result of Division: " +str(a/b))
Output:
Traceback (most recent call last):
File “”, line 1, in
print(“Result of Division: ” +str(x/y))
ZeroDivisionError: division by zero
In the above example, the input code is correct. Still, the program can’t find the output of the input code, so it raises an error related to the result of division as “ ZeroDivisionError”.
For Eg. Let’s create a TypeError error.
Example (5)
def sub():
a=input("Enter a value of a: ")
print('Sub Value:',a-5)
sub()
Output:
Enter a value of a: 6
Traceback (most recent call last):
File “C:\Users\Desktop\example.py”, line 16, in
sub()
File “C:\Users\Desktop\example.py”, line 15, in sub
print(‘Sub Value:’,a-5)
TypeError: unsupported operand type(s) for -: ‘str’ and ‘int’
In the above example, the input code is correct, but we need to convert the input value of ‘a’ an integer, so it raises an error as ” TypeError”.
For Eg. Let’s create a NameError error.
Example (6)
if a==5:
print('a=5')
Output:
Traceback (most recent call last):
File “”, line 1, in
if a==5:
NameError: name ‘a’ is not defined
In the above example, the input code is correct, but the value of ‘a‘ is not defined to compare it in the if statement, so the if statement raises an error as “NameError”.
For Eg. Let’s create an ImportError error.
Example (7)
import flask
Output:
Traceback (most recent call last):
File “”, line 1, in
import flask
ImportError: No module named ‘flask’
In the above code, the input code is correct. Still, when we try to import the flask module, an import statement raises an error as “ImportError” because a flask is not an In-built library module of python, so we can’t import it without installing it in a library file.
Python Exception Handling:
Exception handling is a concept used to handle the exceptions and errors that occur during the execution of any python program. Exceptions are unexpected errors that can occur during code execution.
When an exception occurs, the following things happen in the program:
- Program execution suddenly stops.
- The complete exception message and the code’s file name and line number are printed on the python shell.
- All the calculations and operations performed until the code point are lost.
Exception handling is crucial for handling errors and displaying an appropriate message to the user about the malfunctioning code.
In python, we can handle exceptions using try block, except block and finally block.
A try-except block:
The try block shows the code in which chances of any error to occur, and the except block shows the exceptions and executing the statements specified inside it.
The try block includes the whole code of the program, which will be executed. Suppose any exception occurs during the execution of the try block code. In that case, the execution of the code is to be directed to the except block otherwise, the except block is never executed, and the program pointer is going to the first line after the try-except block.
The except block includes exception cleanup code like a print error message or log error message or trigger some operations. In the except block, we can give a name of the exception class like TypeError, NameError, etc., or directly write the exception message in print statements.
If we provide the name of the exception class, then the except block shows only the exceptions related to the given exception class. So, when we are unsure about the coming exception, don’t mention the exception type’s name in the exception block’s definition.
If we do not provide any exception class name in the except block, then the except block shows all the coming exceptions.
Syntax:
try:
<whole code, which can raise exceptions>
except:
<exception block code, which will be executed to handle exceptions>
For example, after executing the below input code, “ValueError” occurs on the python shell because the div() function accepts integer values for ‘a’ and ‘b’, but we have entered 0.5 for the value of ‘a’.
Example (8)
a=int(input("Enter a value of a: "))
b=int(input("Enter a value of b: "))
def div(a,b):
c=a/b
print("Div value: ",c)
div(a,b)
Output:
If we use the try and except block for the above input code, we can handle this error charmingly, as below.
Example (9)
try:
a=int(input("Enter a value of a: "))
b=int(input("Enter a value of b: "))
def div(a,b):
c=a/b
print("Div value: ",c)
div(a,b)
except:
print("Accept only integer value")
Output:
Enter a value of a: 6.2
Accept only integer value
In the above example, the value of ‘a’ and ‘b’ requires an integer, but we enter the value of ‘a’ as a float, so except block is executed and raises an error message as “Accept only integer value” instead of actual “ValueError”.
If we don’t know the exception details, we can use a generic except block for the user as below.
Example (10)
try:
def sum():
a=input("Enter a value of a: ")
print('Sum Value:',a+5)
sum()
except:
print("Something wrong in a code")
Output:
Enter a value of a: 5
Something wrong with a code
In the above example, the value of ‘a’ is a string, so to add another two values, both values should be required as integer/float/string. So, this code raises an exception message of except block.
If we know the exception detail, we can use the exception classes name in an except block for the developer as below.
Example (11)
try:
a=10
b=int(input("Enter a value of b: "))
def div(a,b):
c=a/b
print("Div value: ",c)
div(a,b)
except ValueError as e:
print(e)
Output:
Enter a value of b: 0.33
ValueError: invalid literal for int() with base 10: ‘0.33’
In the above example, if we take the float value for ‘b’, then except block is executed and raises ValueError as below.
Use of Multiple Exception Classes
Suppose code may generate multiple exceptions in a specific situation or different situations. In that case, we need to use multiple except blocks to handle them or include all exceptions in one except block.
To handle this situation, we can provide the names of the multiple exception classes, separated by a comma in the except block or individually in separate except blocks.
Syntax:
try:
<try block code>
except Exception1:
<except block code1>
except Exception2:
<except block code2>
....
....
except ExceptionN:
<except block codeN>
OR
try:
<try block code>
except Exception1,Exception2,....,ExceptionN:
<except block code>
Here, Exception1/Exception2/…../ExceptionN = Types of exceptions
We can use the above syntax per our program requirement like if we want to handle different exceptions individually, we can catch them in multiple except blocks.
For example, by using of below input code, we can easily handle multiple except blocks for a specific exception.
Example (12)
try:
a=int(input("Enter a value of a: "))
b=int(input("Enter a value of b: "))
def mod(a,b):
c=a%b
print("Modulo value: ",c)
mod(a,b)
except(ValueError):
print("Accept only integer value")
except(ZeroDivisionError):
print("Dividing a number by zero is not allowed")
except :
print("Something wrong in code")
Output:
================ RESTART: C:\Users\Desktop\example.py ================
Enter a value of a: 2
Enter a value of b: 0
Dividing a number by zero is not allowed
================ RESTART: C:\Users\Desktop\example.py ================
Enter a value of a: ‘python’
Accept only integer value
================ RESTART: C:\Users\Desktop\example.py ================
Enter a value of a: 5.5
Accept only integer value
In the above example, if we take the value of ‘a’ /’b’ other than an integer, it will create ValueError. If we take the value of ‘b’ as zero, then the program will create a ZeroDivisionError (number/0), but a third except block is used when the unexpected error comes, which we don’t know. According to this example, we can say that we can print different messages based on exceptions that occurred.
If we don’t want to handle different exceptions individually, then we can catch a set of exceptions in a single except block.
For example, by using the below code, we can handle multiple exceptions in a single except block.
Example (13)
try:
a=int(input("Enter a value of a: "))
b=int(input("Enter a value of b: "))
def mod(a,b):
c=a%b
print("Modulo value: ",c)
mod(a,b)
except(ValueError,ZeroDivisionError) as e:
print("Invalid input value. An input value must be an integer greater than 0")
Output:
================ RESTART: C:\Users\Desktop\example.py ================
Enter a value of a: 2
Enter a value of b: 0
Invalid input value. An input value must be integer greater than 0
================ RESTART: C:\Users\Desktop\example.py ================
Enter a value of a: 2.5
Invalid input value. An input value must be integer greater than 0
In the above example, if we take the value of ‘a’ /’b’ other than integer or then take the value of ‘b’ as zero, then the program will create one error only, so we can say that we can print a single message for multiple exceptions.
In the above example, we can also print the actual exception detail by modifying except block as below.
Example (14)
try:
a=int(input("Enter a value of a: "))
b=int(input("Enter a value of b: "))
def mod(a,b):
c=a%b
print("Modulo value: ",c)
mod(a,b)
except(ValueError,ZeroDivisionError)as e:
print(e)
Output:
================ RESTART: C:\Users\Desktop\example.py ================
Enter a value of a: 8
Enter a value of b: 0.5
invalid literal for int() with base 10: ‘0.5’
================ RESTART: C:\Users\Desktop\example.py ================
Enter a value of a: 10
Enter a value of b: 0
integer division or modulo by zero
In the above example, an error message would be changed according to the input values of ‘a’ and ‘b’.
We can also create the exception inside the except block.
Example (14)
try:
a=int(input("Enter a value of a: "))
b=int(input("Enter a value of b: "))
print("Modulo value: ",a/b)
except:
print("Modulo value: ",a/b)
Output:
Enter a value of a: 12
Enter a value of b: 0
Traceback (most recent call last):
File “C:\Users\Desktop\example.py”, line 4, in
print(“Modulo value: “,a/b)
ZeroDivisionError: division by zero
During the handling of the above exception, another exception occurred:
Traceback (most recent call last):
File “C:\Users\Desktop\example.py”, line 7, in
print(“Modulo value: “,a/b)
ZeroDivisionError: division by zero
In the above example, except block throws the same error two times. The second error occurs after the first error, and mainly second error occurs due to handling the first error.
Use of else Statement with a try-except Block:
We can use the else statement with a try-except block. The statements inside the else block will be executed only if the code inside the try block doesn’t generate any exception.
Syntax:
try:
<try block code >
except exception:
<except block code>
else:
< else block code, which will be executed, if there are no exceptions.>
Example (15)
try:
age=int(input('Enter your age: '))
except:
print ('Invalid value.')
else:
if age <= 18:
print('You are not allowed to enter; you are too young.')
else:
print('Welcome, you are old enough.')
Output:
================ RESTART: C:\Users\Desktop\example.py ================
Enter your age: 15
You are not allowed to enter; you are too young.
================ RESTART: C:\Users\Desktop\example.py ================
Enter your age: a
Invalid value.
================ RESTART: C:\Users\Desktop\example.py ================
Enter your age: 20
Welcome, you are old enough.
In the above example, if we enter the age value as ‘a‘ then the program pointer goes to except block and then executes the code of it, which shows the exception message as “Invalid Value” otherwise program executes the else block and shows the message according to the given integer value of ‘a‘.
The finally Block:
A “finally” block is always used for concluding tasks like closing the DB connection, closing the program with a delightful message, closing the file, etc. It is also used to catch the exceptions, which are not caught by the except block.
It is added after except block. We have already seen many examples without finally block.
For example, Let’s take an example:
Example (16)
try:
a=int(input("Enter a value of a: "))
b=int(input("Enter a value of b: "))
def mod(a,b):
c=a%b
print("Modulo value: ",c)
mod(a,b)
except ValueError:
print("Only accept integer value")
finally :
print("Code to be executed")
Output:
Enter a value of a: 12
Enter a value of b: 0
Code to be executed
Traceback (most recent call last):
File “C:\Users\Desktop\example.py”, line 7, in
mod(a,b)
File “C:\Users\Desktop\example.py”, line 5, in mod
c=a%b
ZeroDivisionError: integer division or modulo by zero
================ RESTART: C:\Users\Desktop\example.py ================
Enter a value of a: 6.2
Only accept integer value
Code to be executed
In the above example, we have not handled ZeroDivisionError in the input code, so the program has stopped execution and thrown an exception after executing the”finally” block in output against the 0 value of ‘b’. We have handled ValueError in the input code, so against the 6.2 value of ‘a’, the program has executed the except block first and then finally block.
Raise Keyword
A raise keyword is used to raise an exception.
Syntax:
raise [Exception [, args [, traceback]]]
Where an exception is the name of the exception class (Eg. NameError), the argument is a value for the exception argument. The argument is optional, and by default, its value is None. The traceback is also optional and used for the exception.
We can use the raise keyword in the try and except block.
For example, use the raise keyword to raise an exception.
Example (17)
a=int(input("Enter a value: "))
b=int(input("Enter b value: "))
try:
if a<0 or b<0:
raise ZeroDivisionError
print(a/b)
except ZeroDivisionError:
print("Please enter valid integer value")
Output:
================ RESTART: C:\Users\Desktop\example.py ================
Enter a value: 20
Enter b value: -1
Please enter valid integer value
================ RESTART: C:\Users\Desktop\example.py ================
Enter a value: 20
Enter b value: 0
Please enter valid integer value
In the above example, if we take 0 or a negative value, then an exception occurs.
A raise keyword works the same as “except“. We can use it in the try, except, and finally blocks and directly in code. It is used to show the last occurred exception. We can use the raise keyword without exception class also.
For example, use the raise without exception class.
Example (18)
try:
a=10
print(b)
except NameError as e:
print("Error Details:",e)
raise
Output:
Error Details: name ‘b’ is not defined
Traceback (most recent call last):
File “C:\Users\Saurav\Desktop\example.py”, line 12, in
print(b)
NameError: name ‘b’ is not defined
In the above example, the ‘b’ value is not defined, so NameError occurs in the output, but it occurs two times; the first line is due to the print statement of except block, and the other lines are due to the use of the raise keyword. A raise keyword shows the last occurred exception.
We can also use the raise keyword with arguments, which is displayed along with the exception class name on the interpreter. We can pass any string to describe the reason for the exception or anything else.
Example (19)
x=4
if x<5:
raise ValueError('x should be greater than 5.')
Output:
Traceback (most recent call last):
File “C:\Users\Desktop\example.py”, line 12, in
raise ValueError(‘x should be greater than 5.’) ValueError: x should be greater than 5.
In the above example, If the value of x is less than 5, then the program will raise an error, which we have given as an attribute in the raise statement.
The assert Keyword:
The assert statement checks whether a given condition is true or false. If the given condition is a false, program execution raises an error as the AssertionError,
Let’s take an example that allows the user to enter a number above or equal to 15.
Example (20)
age=int(input('Enter a age: '))
assert age>=15
print('You entered: ', age)
Output:
================ RESTART: C:\Users\Desktop\example.py ================
Enter age: 10
Traceback (most recent call last):
File “C:\Users\Desktop\example.py”, line 21, in
assert age>=15
AssertionError
================ RESTART: C:\Users\Desktop\example.py ================
Enter age: 15
You entered: 15
In the above example, if the user enters a value below or equal to15, then the assert statement raises an error; otherwise, it executes the print statement.
The assert statement can optionally include an error message string, which gets displayed along with the AssertionError.
Let’s modify the above example as below by adding an error message at the assert statement for negative numbers.
Example (21)
age=int(input('Enter a age: '))
assert age>=15, "Only positive numbers accepted."
print('You entered: ', age)
Output:
Enter age: -20
Traceback (most recent call last):
File “C:\Users\Saurav\Desktop\example.py”, line 21, in
assert age>=15, “Only positive numbers accepted.”
AssertionError: Only positive numbers accepted.
After executing the above code, if the user enters a negative value, the program raises an error and prints the error message of the assert statement.
The AssertionError is a built-in exception and can be handled using the try-except block. We can use multiple assert statements also.
Let’s add a try and except block in the above example below.
Example (22)
try:
age=int(input('Enter a age: '))
assert 0 < age, "Only positive numbers accepted."
assert age>=15, "Only accept number greater than or equal to 15."
print('You entered: ', age)
except AssertionError as e:
print(e)
Output:
================ RESTART: C:\Users\Desktop\example.py ================
Enter age: 16
You entered: 16
================ RESTART: C:\Users\Desktop\example.py ================
Enter age: -2
Only positive numbers are accepted.================ RESTART: C:\Users\Desktop\example.py ================
Enter age: 14
Only accept a number greater than or equal to 15.
We added two assert statements in the above example to check two conditions. Is an entered number a negative number? And Is an entry number below 15. In both conditions, the different message would be printed as AssertionError.
Nested Exception Handling
Sometimes, we need to place one exception-handling statement inside another, like Nested if, Nested loops, etc. This process is often used when we want to obtain the correct type of user input.
For example, if the user enters a non-numeric value, then we will give another chance to the user to enter a valid value.
Example (23)
enter_again = True
while enter_again == True:
try:
age = int(input('Enter your age: '))
except ValueError:
print ('You have to enter a number!')
try:
start_again = int(input('To start again, enter 0. To exit, press any other key. '))
except:
print('OK, you do not want to start again, see you soon!')
enter_again = False
else:
if start_again == 0:
enter_again = True
else:
print('OK, you do not want to start again, see you soon! Exit app.')
enter_again = False
Output:
Enter your age: a
You have to enter a number!
To start again, enter 0. To exit, press any other key. 0
Enter your age: 10
Enter your age: 20
Enter your age: 30
Enter your age: a
You have to enter a number!
To start again, enter 0. To exit, press any other key. 2
OK, you do not want to start again, see you soon! Exit app.
In the above Output, when the user enters a wrong number, the first except block is executed then the program gives another chance to the user to enter a correct number by using a nested try block.
If the user wants to enter a number again, then the user needs to press the ‘0’ value; otherwise, press any key. Here, the user pressed ‘0’, so the else block was executed. After entering 3 different numbers, the user entered an invalid value as ‘a’, so the first except block was again executed and raised an error message.
Then again nested try block asked the user to start this process again, but the user entered ‘2’, which is other than ‘0’, so the nested else block was executed and printed a message as ” OK, you do not want to start again, see you soon!. Exit app.”
Final Words
Errors and exception handling are essential parts of all programming languages, and every language comes with its own built-in exceptions to handle them with your program or application. here in this article, we discussed what errors and exceptions are and how to handle them; we also explained advanced concepts in exception handling, like using multiple exception classes. The last thing we mentioned was the “finnally” section of all exceptions in our program.
If you have an inquiry or doubt don’t hesitate to leave them in the comment section. we are waiting for your feedback.
But remember to understand the concept very well, you need to practice more.
Hopefully, it was clear and concise.