0% found this document useful (0 votes)
146 views

Exception Handling PDF

Exceptions in Python allow programs to handle errors and unexpected conditions gracefully. Common built-in exceptions include ZeroDivisionError, FileNotFoundError, and ImportError. Exceptions are raised when errors occur and can be caught using try/except blocks. Finally blocks ensure code is executed regardless of exceptions. Exceptions can also be raised manually using raise to halt execution under certain conditions.

Uploaded by

Ketki
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
146 views

Exception Handling PDF

Exceptions in Python allow programs to handle errors and unexpected conditions gracefully. Common built-in exceptions include ZeroDivisionError, FileNotFoundError, and ImportError. Exceptions are raised when errors occur and can be caught using try/except blocks. Finally blocks ensure code is executed regardless of exceptions. Exceptions can also be raised manually using raise to halt execution under certain conditions.

Uploaded by

Ketki
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Python Exception Handling

Exceptions in Python
 When writing a program, we may encounter errors.
 An error is called as syntax error or parsing error if the syntax
of a language is not followed.
 Errors can also occur at runtime and these are called
Exceptions.
 They occur
1. When we try to open a file which does not exist
(FileNotFoundError),
2. Dividing a number by zero (ZeroDivisionError),
3. Module we try to import is not found (ImportError) etc.
 Whenever these type of runtime errors occur, Python creates
an exception object.
 If not handled properly, it prints a traceback to that error
along with some details about why that error occurred.
What are exceptions in Python
 There are various built-in exceptions in Python that are
raised when corresponding errors occur.
 Some of the common built-in exceptions in Python
programming along with the error that cause then are
tabulated below.
 For example, if function A calls function B which in turn
calls function C and an exception occurs in function C. If
it is not handled in C, the exception passes to B and then
to A.
 If never handled, an error message is spit out and our
program come to a sudden, unexpected halt.
Python Built-in Exceptions
Exception Cause of Error

NameError Raised when a variable is not found in local or global scope.

MemoryError Raised when an operation runs out of memory.

Raised when a function or operation is applied to an object of


TypeError
incorrect type.

SyntaxError Raised by parser when syntax error is encountered.

ImportError Raised when the imported module is not found.

IndexError Raised when index of a sequence is out of range.

KeyError Raised when a key is not found in a dictionary.

EOFError Raised when the input() functions hit end-of-file condition.


Continued…..
Exception Cause of Error

KeyboardInterrupt Raised when the user hits interrupt key (Ctrl+c or delete).
NotImplementedError Raised by abstract methods.
OSError Raised when system operation causes system related error.
Raised when result of an arithmetic operation is too large to
OverflowError
be represented.
Raised when a weak reference proxy is used to access a
ReferenceError
garbage collected referent.
RuntimeError Raised when an error does not fall under any other category.
AssertionError Raised when assert statement fails.
AttributeError Raised when attribute assignment or reference fails.
Continued…..
Exception Cause of Error

GeneratorExit Raised when a generator's close() method is called.

Raised by next() function to indicate that there is no further


StopIteration
item to be returned by iterator.
IndentationError Raised when there is incorrect indentation.
Raised when indentation consists of inconsistent tabs and
TabError
spaces.
SystemError Raised when interpreter detects internal error.
SystemExit Raised by sys.exit() function.
Raised when a reference is made to a local variable in a function
UnboundLocalError
or method, but no value has been bound to that variable.
Continued…..
Exception Cause of Error

Raised when a Unicode-related encoding or decoding error


UnicodeError
occurs.
UnicodeEncodeError Raised when a Unicode-related error occurs during encoding.
UnicodeDecodeError Raised when a Unicode-related error occurs during decoding.
Raised when a Unicode-related error occurs during
UnicodeTranslateError
translating.
Raised when a function gets argument of correct type but
ValueError
improper value.
Raised when second operand of division or modulo operation
ZeroDivisionError
is zero.
FloatingPointError Raised when a floating point operation fails.
Why use Exceptions?
 Say your program is doing a bunch of calculations, and at some point
you have the line
c = a/b
 If b = 0, you will get a zero division error and the program will
crash.
 Here is an example:

a=3
b=0
c = a/b
print('Hello')

 Output:
ZeroDivisionError: division by zero
Continued…..
 Once the error occurs, none of the code after c=a/b
will get executed.
 The program will just stop running and probably
close.
 When an error occurs, an exception is generated.
 You can catch this exception and allow your program
to recover from the error without crashing.
Catching Exceptions in Python
 In Python, exceptions can be caught using a try statement.
 A critical operation which can raise exception is placed inside
the try clause and the code that handles exception is written
in except clause.
 It is up to us, what operations we perform once we have
caught the exception.
 Syntax:

try:
some statements here
except:
exception handling

 Here is a simple example.


Example
a=3
b=0
try:
c = a/b
except:
print('Error')
print(‘Hello')

Output:
Error
Hello
Catching Specific Exceptions in Python
 In the above example, we did not mention any exception
in the except clause.
 This is not a good programming practice as it will catch
all exceptions and handle every case in the same way.
 We can specify which exceptions an except clause will
catch.
Example
try:
print (1/0)
except ZeroDivisionError:
print ("You can't divide by zero")

Output:
You can't divide by zero

 The error handling is done through the use of exceptions


that are caught in try blocks and handled in except blocks.
 If an error is encountered, a try block code execution is
stopped and transferred down to the except block.
Example
try:
f = open('somefile.txt', 'r')
print(f.read())
f.close()
except IOError:
print('file not found')
Multiple Exceptions
 A try clause can have any number of except clause to
handle them differently but only one will be executed in
case an exception occurs.
Example
try:
a = int(input('Enter a number: '))
print (3/a)
except ValueError:
print('Please enter a number.')
except ZeroDivisionError:
print("Can't enter 0.")
Multiple Exceptions with Tuples
 Python allows us to include multiple exceptions in a single
except clause using tuples.
 However, in this case, the except block will execute only a
single block of statements.
 Syntax:

try:
some statements here
Except (exception1, exception2,exception3):
exception handling
Example
try:
a = int(input('Enter a number: '))
print (3/a)
except (ValueError, ZeroDivisionError):
print('Something went wrong')

 Output:
Enter a number: d
Something went wrong
Enter a number: 0
Something went wrong
exception ArithmeticError
 This class is the base class for those built-in exceptions
that are raised for various arithmetic errors such as
1. OverflowError
2. ZeroDivisionError
3. FloatingPointError
try…. else
try:
a = 10/0
print (a)
except ArithmeticError:
print ("Arithmetic exception raised." )
else:
print ("Success.")

Output:
Arithmetic exception raised
try….finally
 You can use a finally: block along with a try: block.
 Finally block consists of the finally keyword.
 It is placed after the last except block.
 It is intended to define clean-up actions that must be executed under all
circumstances.
 If an exception is thrown, the finally block will execute even if no except
statement matches that exception.
 Syntax:

try:
You do your operations here; ......................
except :
Handle exception
finally:
This would always be executed. ......................
Example
a=3
b=0
try:
print(a/b)
except ZeroDivisionError:
print("Something went wrong")
finally:
print("Printed finally")

 Output:
Something went wrong
Printed finally
Raising Exception:
 The raise statement can be used by the programmers to
raise their own exceptions.
 User-triggered exceptions are caught the same way as
they are raised by Python.
 This is useful if you are writing your own classes to be
used in other programs and you want to send messages,
like error messages, to people who are using your class.
 The only argument in raise indicates the exception to be
raised.
 Syntax:

raise [Exception [, args]]


Continued…..
 If you want to throw an error when a certain condition occurs using raise,
you could go about it like this:

x = 10
try:
if x > 5:
raise Exception
except Exception:
print('X should not exceed 5')

 Output:
Traceback (most recent call last):
File "<input>", line 4, in <module>
Exception: x should not exceed 5

 The program comes to a halt and displays our exception to screen, offering
clues about what went wrong.
The AssertionError Exception
 Instead of waiting for a program to crash midway, you can also
start by making an assertion in Python.
 We assert that a certain condition is met.
 If this condition turns out to be True, then that is excellent!
The program can continue.
 If the condition turns out to be False, you can have the
program throw an AssertionError exception.
Example
import sys
assert ('linux' in sys.platform), “Code runs on Linux only.”

 If you run this code on a Linux machine, the assertion passes.


 If you were to run this code on a Windows machine, the outcome of the
assertion would be False and the result would be the following:

Traceback (most recent call last):


File "<input>", line 2, in <module>
AssertionError: This code runs on Linux only.

 In this example, throwing an AssertionError exception is the last thing that


the program will do.
 The program will come to halt and will not continue.
Find Output
L1 = [1,2,3,4,5]
try:
print(L1)
n = int(input("Enter the index to print the element"))
print("Index =", n, "Element = ", L1[n])
except IndexError:
print("Please check the Index")
finally:
print("No one can strop me from running")
Find Output
def enterage(age):
if age < 0:
raise ValueError
if age % 2 == 0:
print("age is even")
else:
print("age is odd")

try:
num = int(input("Enter your age: "))
enterage(num)

except ValueError:
print("Only positive integers are allowed")
Find Output
try:
with open('new.txt') as file:
read_data = file.read()
print(read_data)
except:
print('Could not open file.log')
Find Output
try:
a=3
if a < 4:
b = a / (a - 3)
print("Value of b = ", b)
except(ZeroDivisionError, NameError):
print("Error Occurred and Handled")

You might also like