11.Exception Handling in python.docx
11.Exception Handling in python.docx
Website: https://pythonlife.in/
in
of the program is prevented.
Python uses try and except keywords to handle exceptions. Both keywords are
followed by indented blocks.
e.
Syntax:
try :
lif
#statements in try block
except :
on
#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
th
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.
Py
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.
2
Website: https://pythonlife.in/
The rest of the statements after the except block will continue to be executed,
regardless if the exception is encountered or not.
in
a=5
b='0'
e.
print(a/b)
except:
lif
print('Some error occurred.')
You can mention a specific type of exception in front of the except keyword.
Py
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.
3
Website: https://pythonlife.in/
Example: Catch Specific Error Type
try:
a=5
b='0'
print (a+b)
except TypeError:
in
print('Unsupported operation')
e.
Output
Unsupported operation
try:
a=5
b=0
Py
print (a/b)
except TypeError:
print('Unsupported operation')
except ZeroDivisionError:
in
else and finally:
e.
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.
lif
Syntax:
on
try:
except:
else:
finally:
As a consequence, the error-free try block skips the except clause and
enters the finally block before going on to execute the rest of the code.
5
Website: https://pythonlife.in/
If, however, there's an exception in the try block, the appropriate except
block will be processed, and the statements in the finally block will be
processed before proceeding to the rest of the code.
The example below accepts two numbers from the user and performs their
division. It demonstrates the uses of else and finally blocks.
in
print('try block')
e.
z=x/y
except ZeroDivisionError:
print("else block")
print("Division = ", z)
finally:
th
print("finally block")
x=0
Py
y=0
Output
try block
Enter a number: 49
in
else block
Division = 7.0
finally block
e.
Out of try, except, else and finally blocks.
The second run is a case of division by zero, hence, the except block and
lif
the finally block are executed, but the else block is not executed.
Output
on
try block
Enter a number: 10
finally block
Py
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.
7
Website: https://pythonlife.in/
Output
try block
Enter a number: 10
finally block
in
File "C:\python36\codes\test.py", line 3, in <module>
e.
Typically the finally clause is the ideal place for cleaning up the operations
in a process. For example closing a file irrespective of the errors in
read/write operations. This will be dealt with in the next chapter.
lif
on
th
Py
8
Website: https://pythonlife.in/
Raise an Exception
Python also provides the raise keyword to be used in the context of
exception handling.
in
Built-in errors are raised implicitly.
e.
The following code accepts a number from the user.
The try block raises a ValueError exception if the number is outside the
lif
allowed range.
if x > 100:
th
raise ValueError(x)
except ValueError:
Py
else:
Output
Enter a number upto 100: 200
in
50 is within the allowed range
e.
Here, the raised exception is a ValueError type. However, you can define
your custom exception type to be raised. Visit Python docs to know more
about user defined exceptions
lif
on
th
Py