Exception Handling
Exception Handling
Presented By:
Dept. of Computer Science, KDARFS, Jamnagar
Syllabus (2023-24)
(ii) It clarifies the code (by removing error-handling code from main line of
program) and enhances readability.
(iii) It stimulates consequences as the error-handling takes place at one place and
in one manner.
Invalid input
When a Python code throws an exception, it has two options: handle the
exception immediately or stop and quit.
Example (Syntax Error)
When the interpreter identifies a statement that has an error, syntax errors occur.
Consider the following scenario:
There was one unclosed bracket in this case. Close it and return the program:
Example (Run-time Error)
Exception Handling in Python involves the use of try and except clauses in
the following format
See, now the output produced does not show the scary red-coloured standard error message ; it is now
showing what you defined under the exception block.
Write a program to ensure that an integer is entered as input and in case any other
value is entered, it displays a message – ‘Not a valid integer’
ok = False
while not ok :
try :
numberString = input("Enter an integer:")
n = int(numberString)
ok = True
except :
print ("Error! Not a valid integer.")
Program to handle exception while opening a file.
try:
my_file = open("myfile.txt", "r")
print (my_file.read())
except:
print ("Error opening file")
The above program will open the file successfully if the file myfile.txt exists and contains some data
otherwise it shows an output as :
But the above code did not tell which caused the error
You can also provide a second argument for the except block, which gives a reference to the
exception object. You can do it in following format :
try:
# code
except <ExceptionName> as <exArgument> :
# handle error here
Handling Multiple Errors
• Multiple types of errors may be captured and processed differently.
• It can be useful to provide a more exact error message to the user than a simple “an error has
occurred.”
• In order to capture and process different type of exceptions, there must be multiple exception blocks
– each one pertaining to different type of exception.
The last else : clause will execute if there is no exception raised, so you may put your code that
you want to execute when no exceptions get raised.
Exception Handling – execution order
You can also use a finally: block along with a try: block, just like you use except:
block, e.g., as :
The difference between an except: block and the finally: block is that the finally: block is a place
that contains any code that must execute, whether the try: block raised an exception or not.
Raising/Forcing an Exception(raise Statement)
You may use the raise keyword to raise/force an exception. That means, you as
programmer can force an exception to occur through raise keyword. It can also pass a
custom message to your exception handling module.
try :
a = int(input("Enter numerator :"))
b = int(input("Enter denominator :"))
if b == 0 :
raise ZeroDivisionError(str(a) + "/0 not possible")
print (a/b)
except ZeroDivisionError as e :
print ("Exception", str(e))
The assert Statement
An assert statement in Python is used to test an expression in the program code.
If the result after testing comes false, then the exception is raised.
This statement is generally used in the beginning of the function or after a function call to
check for valid input.