Exception Handling in Python
Exception handling in Python is a mechanism that allows you to handle errors and unexpected situations that occur during the execution of a program. It helps in gracefully managing errors and preventing your program from crashing. Python provides a built-in way to handle exceptions using the try, except, else, and finally blocks.
Here's a basic structure of exception handling in Python:
pythonCopy codetry:
# Code that may raise an exception
# ...
except ExceptionName1:
# Code to handle ExceptionName1
# ...
except ExceptionName2:
# Code to handle ExceptionName2
# ...
else:
# Code that runs if no exceptions occurred in the try block
# ...
finally:
# Optional block of code that always runs, regardless of whether an exception occurred or not
# ...
The
tryblock contains the code that might raise an exception.The
exceptblock(s) catch and handle specific exceptions. You can have multipleexceptblocks to handle different types of exceptions.The
elseblock is optional and runs if no exceptions occurred in thetryblock.The
finallyblock is also optional and runs regardless of whether an exception occurred or not. It is typically used for cleanup actions (e.g., closing files or releasing resources).
Here's an example demonstrating how exception handling works in Python:
pythonCopy codetry:
x = int(input("Enter a number: "))
result = 10 / x
print("Result:", result)
except ZeroDivisionError:
print("Error: Division by zero!")
except ValueError:
print("Error: Invalid input! Please enter a valid number.")
else:
print("No exceptions occurred.")
finally:
print("Exiting the program.")
In this example:
If the user enters
0, aZeroDivisionErrorwill be raised, and the correspondingexceptblock will handle it.If the user enters a non-numeric value (e.g.,
"abc"), aValueErrorwill be raised, and its correspondingexceptblock will handle it.If the user enters a valid number other than
0, the division operation will be performed, and theelseblock will run.Finally, the
finallyblock will always run, regardless of whether an exception occurred or not.
Exception handling in Python allows you to write robust and reliable code by handling errors gracefully and providing meaningful feedback to users.
Check out more resources: