Python Exception Handling
Python Exception Handling
Python Exceptions
When a Python program meets an error, it stops the execution of the rest of the
program. An error in Python might be either an error in the syntax of an expression
or a Python exception. We will see what an exception is. Also, we will see the
difference between a syntax error and an exception
What is an Exception?
When a Python code throws an exception, it has two options: handle the exception
immediately or stop and quit.
Syntax Error: As the name suggests this error is caused by the wrong syntax in the
code. It leads to the termination of the program.
When the interpreter identifies a statement that has an error, syntax errors occur.
Consider the following scenario:
amount = 10000
for s in string:
if (s != o:
print( s )
Output:
if (s != o:
^
SyntaxError: invalid syntax
The arrow in the output shows where the interpreter encountered a syntactic error.
There was one unclosed bracket in this case. Close it and rerun the program:
Exceptions: Exceptions are raised when the program is syntactically correct, but the
code results in an error. This error does not stop the execution of the program,
however, it changes the normal flow of the program.
Output:
ZeroDivisionError
Code
# Python code after removing the syntax error
# string = "Python Exceptions"
#
# for s in string1:
# if ('s' != 'o'):
# print(s) #NameError
In Python, there are several built-in exceptions that can be raised when an error
occurs during the execution of a program. Here are some of the most common
types of exceptions in Python:
SyntaxError: This exception is raised when the interpreter encounters a
syntax error in the code, such as a misspelled keyword, a missing colon,
or an unbalanced parenthesis.
TypeError: This exception is raised when an operation or function is
applied to an object of the wrong type, such as adding a string to an
integer.
NameError: This exception is raised when a variable or function name is
not found in the current scope.
IndexError: This exception is raised when an index is out of range for a
list, tuple, or other sequence types.
KeyError: This exception is raised when a key is not found in a dictionary.
ValueError: This exception is raised when a function or method is called
with an invalid argument or input, such as trying to convert a string to an
integer when the string does not represent a valid integer.
AttributeError: This exception is raised when an attribute or method is
not found on an object, such as trying to access a non-existent attribute
of a class instance.
IOError: This exception is raised when an I/O operation, such as reading
or writing a file, fails due to an input/output error.
ZeroDivisionError: This exception is raised when an attempt is made to
divide a number by zero.
ImportError: This exception is raised when an import statement fails to
find or load a module.
These are just a few examples of the many types of exceptions that can occur in
Python. It’s important to handle exceptions properly in your code using try-except
blocks or other error-handling techniques, in order to gracefully handle errors and
prevent the program from crashing.
The try block lets you test a block of code for errors.
The else block lets you execute code when there is no error.
The lets you execute code, regardless of the result of the try- and except blocks.
The cause of an exception is often external to the program itself. For example, an
incorrect input, a malfunctioning IO device etc. Because the program abruptly
terminates on encountering an exception, it may cause damage to system
resources, such as files. Hence, the exceptions should be properly handled so that
an abrupt termination of the program is prevented.
Python uses try and except keywords to handle exceptions. Both keywords are
followed by indented blocks.
Syntax:
try :
#statements in try block
except :
#executed when error in try block
The try: block contains one or more statements which are likely to encounter an
exception. If the statements in this block are executed without an exception, the
subsequent except: block is skipped.
If the exception does occur, the program flow is transferred to the except: block.
The statements in the except: block are meant to handle the cause of the exception
appropriately. For example, returning an appropriate error message.
You can specify the type of exception after the except keyword. The subsequent
block will be executed only if the specified exception occurs. There may be
multiple except clauses with different exception types in a single try block. If the
type of exception doesn't match any of the except blocks, it will remain unhandled
and the program will terminate.
The rest of the statements after the except block will continue to be executed,
regardless if the exception is encountered or not.
The following example will throw an exception when we try to devide an integer
by a string.
try:
a=5
b='0'
print(a/b)
except:
print('Some error occurred.')
print("Out of try except blocks.")
Output
Some error occurred.
Out of try except blocks.
x=5
y = "hello"
try:
z=x+y
except TypeError:
print("Error: cannot add an int and a str")
Output
Error: cannot add an int and a str
try:
even_numbers = [2,4,6,8]
print(even_numbers[5])
except ZeroDivisionError:
print("Denominator cannot be 0.")
except IndexError:
print("Index Out of Bound.")
You can mention a specific type of exception in front of the except keyword. The
subsequent block will be executed only if the specified exception occurs. There
may be multiple except clauses with different exception types in a single try block.
If the type of exception doesn't match any of the except blocks, it will remain
unhandled and the program will terminate.
Output
Unsupported operation
Out of try except blocks
As mentioned above, a single try block may have multiple except blocks. The
following example uses two except blocks to process two different exception
types:
In Python, keywords else and finally can also be used along with the try and except
clauses. While the except block is executed if the exception occurs inside the try
block, the else block gets processed if the try block is found to be exception free.
Syntax:
try:
#statements in try block
except:
#executed when error in try block
else:
#executed if try block is error-free
finally:
#executed irrespective of exception occured or not
The example below accepts two numbers from the user and performs their
division. It demonstrates the uses of else and finally blocks.
The first run is a normal case. The out of the else and finally blocks is displayed
because the try block is error-free.
Output
try block
Enter a number: 10
Enter another number: 2
else block
Division = 5.0
finally block
Out of try, except, else and finally blocks.
The second run is a case of division by zero, hence, the except block and the finally
block are executed, but the else block is not executed.
Output
try block
Enter a number: 10
Enter another number: 0
except ZeroDivisionError block
Division by 0 not accepted
finally block
Out of try, except, else and finally blocks.
In the third run case, an uncaught exception occurs. The finally block is still
executed but the program terminates and does not execute the program after the
finally block.
Output
try block
Enter a number: 10
Enter another number: xyz
finally block
Traceback (most recent call last):
File "C:\python36\codes\test.py", line 3, in <module>
y=int(input('Enter another number: '))
ValueError: invalid literal for int() with base 10: 'xyz'
finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed')
Output:
Can't divide by zero
This is always executed