Exception Handling in Python
Definition
● An exception is an error that occurs during the execution of a program
and disrupts the normal flow of instructions.
● Exception handling is a mechanism in Python to gracefully handle
runtime errors, so the program does not crash abruptly.
Basic Example
try:
num = int(input("Enter a number: "))
print("Reciprocal is:", 1/num)
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
except ValueError:
print("Error: Invalid input, please enter an integer.")
Handling Multiple Exceptions
You can write multiple except blocks for different error types.
try:
x = int("abc") # causes ValueError
y = 10 / 0 # causes ZeroDivisionError
except ValueError:
print("Invalid conversion!")
except ZeroDivisionError:
print("Cannot divide by zero.")
Multiple Exceptions in a Single Except Block
You can handle multiple exceptions using a tuple.
try:
a = int("hello")
except (ValueError, TypeError) as e:
print("Error occurred:", e)
Using a Generic except:
● except: without specifying an error type catches all exceptions, but it
is not recommended as it hides errors.
try:
result = 10 / 0
except:
print("Some error occurred.")
Using except Exception as e:
● Best practice is to catch all exceptions using Exception, the base class
for most built-in exceptions.
● This also gives an error message for debugging.
try:
result = 10 / 0
except Exception as e:
print("Error:", e)
Output:
Error: division by zero
Using else Block
● else executes only if no exception occurs.
try:
num = int(input("Enter number: "))
print("Square:", num**2)
except ValueError:
print("Invalid number!")
else:
print("Execution successful, no error.")
Using finally Block
● The finally block executes always (whether exception occurs or not).
● Useful for releasing resources (files, DB connections).
try:
f = open("[Link]", "r")
content = [Link]()
except FileNotFoundError:
print("File not found.")
finally:
print("Closing file (if opened).")
try:
[Link]()
except:
pass
Predict Output Questions
Q1:
try:
print(10/0)
except ZeroDivisionError:
print("Handled")
finally:
print("Done")
Output:
Handled
Done
Q2:
try:
print("Start")
x = int("abc")
except:
print(“Some error occurred”)
except ValueError:
print("Value Error")
else :
print("No Error")
finally:
print("End")
Output:
Start
Some error occurred
End
Q3:
try:
x = 5
y = x / 5
except ZeroDivisionError:
print("Zero Division")
else:
print("No Exception:", y)
finally:
print("Finished")
Output:
No Exception: 1.0
Finished