Python Exception Handling
An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.
Exceptions occurs in a program when the normal flow of execution is disrupted by unexpected events, such as invalid user input, missing files, network errors, or logical errors in the code.
Exception handling is a mechanism that allows developers to detect, manage, and respond to runtime errors in a structured and controlled way. If exceptions are not handled properly, the program may terminate abruptly, lose important data, expose sensitive information through error messages, or behave unpredictably, ultimately leading to a poor user experience.
The try and except Block
In Python, you handle exceptions using try and except blocks. You place the code that might raise an exception inside the try block, and define how the program should respond in an except block if an error occurs.
try:
number = int(input("Enter a number: "))
result = 100 / number
print(result)
except ZeroDivisionError:
print("Error: You cannot divide by zero.")
The above code raise ZeroDivisionError if the user enters 0, since division by zero is not allowed.
Handling Multiple Exceptions
A single block of code can raise different types of exceptions, each of which may require a different handling strategy.
You can use multiple except clauses to catch and handle each possible error appropriately.
try:
number = int(input("Enter a number: "))
result = 100 / number
print(result)
except ZeroDivisionError:
print("Error: You cannot divide by zero.")
except ValueError:
print("Error: Please enter a valid integer.")
The above code raise ZeroDivisionError if the user enters 0, since division by zero is not allowed. Also it raises ValueError if the input cannot be converted to an integer (for example, if the user enters text or a decimal number).
Catching Multiple Exceptions in One Block
If multiple exceptions need to be handled the same way, you can use a single except block with a tuple of exception types.
try:
number = int(input("Enter a number: "))
result = 100 / number
print(result)
except (ZeroDivisionError, ValueError):
print("Division by zero or invalid input.")
Using as to Access Exception Details
You can use as in an except block to capture the exception object and access its details. This allows you to log or inspect the error message.
try:
number = int(input("Enter a number: "))
result = 100 / number
print(result)
except (ZeroDivisionError, ValueError) as e:
print("Error: ", e)
The else Clause
The try/except block can be extended with an else clause. The else block runs only if the try block completes without raising an exception. This is perfect for code that should execute only when everything went smoothly, and it helps keep your try block focused on the lines that might fail.