Exception Handling 5
Exception Handling 5
Exception Handling
• Exception Handling
• An exception can be defined as an unusual condition in a program
resulting in the interruption in the flow of the program.
• Whenever an exception occurs, the program stops the execution,
and thus the further code is not executed. Therefore, an exception
is the run-time errors that are unable to handle to Python script. An
exception is a Python object that represents an error
• Python provides a way to handle the exception so that the code can
be executed without any interruption. If we do not handle the
exception, the interpreter doesn't execute all the code that exists
after the exception.
• Handling of exception ensures that the flow of the program does
not get interrupted when an exception occurs which is done by
trapping run-time errors. Handling of exceptions results in the
execution of all the statements in the program.
• Common Exceptions
• Python provides the number of built-in exceptions, but here we are
describing the common standard exceptions. A list of common
exceptions that can be thrown from a standard Python program is
given below.
• ZeroDivisionError: Occurs when a number is divided by zero.
• NameError: It occurs when a name is not found. It may be local or
global.
• IndentationError: If incorrect indentation is given.
• IOError: It occurs when Input Output operation fails.
• EOFError: It occurs when the end of the file is reached, and yet
operations are being performed.
• The try-expect statement
• If the Python program contains suspicious code that may throw the
exception, we must place that code in the try block. The try block
must be followed with the except statement, which contains a
block of code that will be executed if there is some exception in the
try block.
Syntax
try:
#block of code
except Exception1:
#block of code
except Exception2:
#block of code
#other code
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
except:
print("Can't divide with zero")
The syntax to use the else statement with the try-except statement is
given below.
try:
#block of code
except Exception1:
#block of code
else:
#this code executes
if no except block is executed
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b = %d"%c)
# Using Exception with except statement. If we print(Exception) it will
return exception class
except Exception:
print("can't divide by zero")
print(Exception)
else:
print("Hi I am else block")
• The try...finally block
• Python provides the optional finally statement, which is used with
the try statement. It is executed no matter what exception occurs
and used to release the external resource. The finally block provides
a guarantee of the execution.
• We can use the finally block with the try block in which we can pace
the necessary code, which must be executed before the try
statement throws an exception.
• Syntax
try:
# block of code
# this may throw an exception
finally:
# block of code
# this will always be executed
• How the try and except works –
• First try clause is executed i.e. the code
between try and except clause.
• If there is no exception, then only try clause will run, except clause
will not get executed.
• If any exception occurs, the try clause will be skippeed
and except clause will run.
• If any exception occurs, but the except clause within the code
doesn’t handle it, it is passed on to the outer try statements. If the
exception is left unhandled, then the execution stops.
• A try statement can have more than one except clause.
try:
fileptr = open("file2.txt","r")
try:
fileptr.write("Hi I am good")
finally:
fileptr.close()
print("file closed")
except:
print("Error")
Program to Check for ZeroDivisionError Exception
x = int(input("Enter value for x: "))
y = int(input("Enter value for y: "))
try:
result = x / y
except ZeroDivisionError:
print("Division by zero!")
else:
print(f"Result is {result}")
finally:
print("Executing finally clause")
• File Operation
try:
fh = open ("testfile", "w")
fh.write ("This is my test file for exception handling!!")
finally:
print "Error: can\'t find file or read data“
If you do not have permission to open the file in writing mode, then
this will produce the following result −
Error: can't find file or read data
try:
fh = open("testfile", "w")
try:
fh.write("This is my test file for exception handling!!")
finally:
print "Going to close the file"
fh.close()
except IOError:
print "Error: can\'t find file or read data“