Chapter 7
Chapter 7
Chapter 7
PROGRAMMING USING
PYTHON
1
EXCEPTIONS
Dr Vipan Arora
Errors
2
Dr Vipan Arora
Syntax Errors
3
Dr Vipan Arora
5
(a,b) = (6,0)
# simple use of try-except block for handling errors
try:
g = a/b
except ZeroDivisionError:
print ("This is a DIVIDED BY ZERO error")
Output
This is a DIVIDED BY ZERO error
Dr Vipan Arora
Processing of Exceptions
8
Dr Vipan Arora
Try Expect
9
Dr Vipan Arora
How try() works?
10
Dr Vipan Arora
Python code to illustrate working of try()
11
Dr Vipan Arora
Else Clause
12
In python, you can also use the else clause on the try-except
block which must be present after all the except clauses. The
code enters the else block only if the try clause does not raise
an exception.
Try:
# Some Code
except:
# Executed if error in the
# try block
else:
# execute if no exception
Dr Vipan Arora
Finally Keyword in Python
13
Dr Vipan Arora
15
Dr Vipan Arora
Raise statement
16
Dr Vipan Arora
Handling Multiple Exceptions
17
Python has many built in exceptions that are raised when your
program encounters an error (something in the program goes
wrong).
When these exceptions occur, the Python interpreter stops the
current process and passes it to the calling process until it is
handled. If not handled, the program will crash.
For example, let us consider a program where we have
a function A that calls function B, which in turn calls function C.
If an exception occurs in function C but is not handled in C, the
exception passes to B and then to A.
If never handled, an error message is displayed and our program
comes to a sudden unexpected halt.
Python allows us to handle multiple exceptions in 2 ways:
Dr Vipan Arora
1. Using Multiple Except Blocks
18
try:
pass
except Exception1:
pass
except Exception2:
pass
Dr Vipan Arora
2. Using a Single Except Block
19
Dr Vipan Arora