You are on page 1of 10

Exception handling

• Python has many built-in exceptions that are raised when your
program encounters an error
• If exceptions are not handled then program comes to a sudden
unexpected halt.
Catching Exceptions in Python
• Exceptions can be handled using a try statement.
• Operation which can raise an exception is placed inside the try clause.
• The code that handles the exceptions is written in the except clause.
try:
a=int(input(‘enter a number string’)
except:
print(‘a needs number string only)
Exception Class
• Every exception in Python inherits from the base Exception class.
• We can also perform the previous task in the following way:

try:
a=int(input('enter a number string'))
except Exception as e:
print('exception', e.__class__, 'occured')
Catching Specific Exceptions in Python
• There are many inbuilt exceptions some of the most important are:
• ValueError try:
a=int(input('enter a number'))
• TypeError b=int(input('enter a number'))
try:
• ZeroDivisionError a=a/b
except ZeroDivisionError as z:
print('exception', z.__class__,'occur')

except ValueError as v:
print('exception', v.__class__,'occur')
try with else clause
# program to print the reciprocal of even numbers

try:
num = int(input("Enter a number: ")) In some situations, you might want to
run a certain block of code if the code
assert num % 2 == 0 block inside try ran without any errors.
except: For these cases, you can use the
optional else keyword with the try
print("Not an even number!") statement.
else:
The code enters the else block only if
reciprocal = 1/num the try clause does not raise an
print(reciprocal) exception.
try with finally
try: The try statement in Python
can have an optional finally
f = open("test.txt") clause. This clause is executed
# perform file operations no matter what, and is
generally used to release
finally: external resources.

f.close()
User defined exception
(custom exception)
List Comprehension
• Elegant way of creating list using for loop with less code.
Generator Expressions

Difference:
1. The generator yields one item at a time and generates item only when in demand. Whereas, in a list
comprehension, Python reserves memory for the whole list. Thus we can say that the generator expressions
are memory efficient than the lists.
2. Generators are memory and space efficient than comprehension.
Time and Space comparison:
Comprehension vs Generator

You might also like