Exception Handling
Exception Handling
Exception Handling
What is Exception?
Unexpected situation or errors occur during the program execution is known as
Exception. This will lead to the termination of program execution. For this programmer
have no control on.
Egs. ATM machine running out of cash, When you try to open a file that does not exit in
that path. These type of anomalous situations are generally called exceptions and the way
to handle them is called exception handling.
Example:
>>>l1=[1,2,3]
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
l1[4]
IndexError: list index out of range
Concept of Exception handling:
1. Write a code in such a way that it raises some error flag every time something goes
wrong
2. Then trap this error flag and if this is spotted, call the error handling routine.
• Raising an imaginary error flag is called throwing or raising an error
• When error is thrown, the overall system responds by catching the error.
• The surrounding a block of error-sensitive-code-with-exception-handling is called trying
to execute a block.
Write code such that it If error flag Call the error handling
raises an error-flag
routine
every time something
-------------------------------
goes wrong Is raised then Catch exception
-------------------------------
Throw exception
Terminology used with exception handling:
Description Python terminology
An unexpected error that occurs during Exception
runtime
A set of code that might have an Try block
exception thrown in it
The process by which an exception is Catching
generated and executing atatements that
try to resolve the problem
The block of code that attempts to deal Except clause for except/exception block
with the exception (ie. Problem) or catch block
The sequence of method calls that Stack trace
brought control to the point where the
exception occurred
When to use Exception Handling:
Processing exception situation
Processing exception for components that cannot handle them directly
Large projects that require uniform error-processing.
try:
a,b=int(input("enter a no")),int(input("enter a divisor"))
print(a/b)
except:
print("Division by Zero ! denominator must not be zero")
Output 1:
enter a no6
enter a divisor3
result of a/b 2.0
Output2:
enter a no6
enter a divisor0
Division by Zero ! denominator must not be zero
General built-in Python Exception:
Program to handle exception while opening a file
try:
myf=open("d:/myf.txt",'r')
print(myf.read())
except:
print("Error opening a file")
OUTPUT:
Hello python
The above output is displayed if the file has been opened for reading successfully.
Otherwise it shows ‘Error opening a file’
Exception raised because of TypeError and ValueError:
import traceback
try:
a=5
b=int(input("enter a no."))
print(a+b)
print(a+"five")
except ValueError:
print("arithmetic is not possible between a no. and string")
except TypeError:
print("cannot convert a string to a number")
Second argument of the except block:
try:
# code
Except <ExceptionName> as <exArgument>:
# handle error file
try:
print("result of 5/0=",5/5)
print("result of 5/0=",5/0)
except ZeroDivisionError as e:
print("Exception raised",e)
Output:
result of 5/0= 1.0
Exception raised division by zero
Handling multiple errors:
Multiple exception blocks – one for each exception raised.
This will give exact error message for a specific exception than having one common
error message for all exception.
try:
#:
except <exceptionName1>:
#:
except <exceptionName1>:
#:
except :
#:
else:
#if there is no exception then the statements in this block get executed.
Example:
try:
my_file=open('d:\myf.txt')
my_line=my_file.readline()
my_int=int(s.strip())
my_calc=101/my_int
print(my_calc) When <try suite> is executed, an exception
except IOError: occurs, the <except suite> is executed with
print('I/O error occurred') name bound if found; otherwise unnamed
except ValueError: except suite is executed.
print('Division by zero error')
except ZeroDivisionError:
print("unexpected error")
except:
print('unexpected error')
else:
print('No exceptions')
Finally block:
Finally block can be used just like except block but any code placed inside finally block
must execute, whether the try block raised an exception or not.
try:
#statements that may raise exception
[except:
# handle exception here]
finally:
#statements that will always run
Example:
try:
fh=open(“poems.txt” , ”r+”)
fh.write(“Adding new line”)
except: The except block is executed only when
print(“Exception has occurred”) exception has occurred but finally block
finally: will be executed always in the end.
print(“goodbye!!!”)
Raising/Forcing an Exception:
Raise keyword can be used to raise/force an exception.
The programmer can force an exception to occur through raise keyword with a custome
message to the exception handling module.
Raise <exception>(<message>)
It is a predefined built-in exception.
Example:
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”, e)