Exception Handling

try:

a = 1 / 0

except:

print('Except block executed.')

try:

a = 1 / 0

except Exception as e:

print(e)

# Will print “e”

try:

a = 1 / 0

except ZeroDivisionError as e:

print(e)



division by zero

# Won’t catch exception because specified type doesn’t match exception - Program will crash

try:

a = 1 / 0

except TypeError as e:

print(e)

try:

a = 1 / 0

except (ZeroDivisionError, TypeError) as e:

print(e)


The try-except logic can be expanded further with an else statement and code block. The code in a grouped else statement only runs if the try code block completes with no Exceptions.

try:

a = 1

except (ZeroDivisionError, TypeError) as e:

print(e)

else:

print('No Exception Raised')

try:

a = 1

except (ZeroDivisionError, TypeError) as e:

print(e)

else:

print("No Exception Raised")

finally:

print("Finished")



No Exception Raised

Finished

try:

a = 1 / 0

except (ZeroDivisionError, TypeError) as e:

print(e)

else:

print("No Exception Raised")

finally:

print("Finished")



division by zero

Finished


Raise

With the raise keyword, you can throw your own Exceptions. For example, you could use conditional logic to check for a certain condition. As shown below, you can return a general Exception object providing an input string.

val = input("Enter a number less than 0")

If (int(val) >= 0):

raise Exception("You entered a number greater than or equal to 0")


You can also raise a specific type of exception, such as a TypeError.

data = [1, 2.1, 3, 2.2]

x = data[2]


if (not type(x) is float):

raise TypeError("Only floats allowed")



TypeError: Only floats allowed