Exceptions in Python
? Exceptions in Python
In Python, exceptions are events that can modify the flow of control through a program. They are typically used to handle errors in a more structured way. When an error occurs, Python will raise an exception, which can be caught and handled, allowing your program to continue running instead of crashing.
Here’s a breakdown of how exceptions work in Python:
? 1. Basic Structure of an Exception
When an error occurs in Python, an exception is raised. Python provides a way to catch these exceptions using a try...except block. The basic syntax is as follows:
try: # Code that may raise an exception x = 1 / 0 # This will raise a ZeroDivisionErrorexcept ZeroDivisionError: # Code to handle the exception print("Cannot divide by zero!")In the above example:
The code inside the
tryblock attempts to execute the division, which raises aZeroDivisionError.The
exceptblock catches this specific error and prints a message.
? 2. Common Built-in Exceptions
Python provides a variety of built-in exceptions for common error types:
ZeroDivisionError: Raised when dividing by zero.TypeError: Raised when an operation is performed on an object of inappropriate type.ValueError: Raised when a function receives an argument of the right type but inappropriate value.IndexError: Raised when trying to access an index that is out of range.KeyError: Raised when a dictionary key is not found.FileNotFoundError: Raised when trying to open a file that does not exist.
? 3. Catching Multiple Exceptions
You can catch multiple types of exceptions by specifying multiple except blocks:
try: # Some code that could raise different exceptions x = int(input("Enter a number: ")) result = 10 / xexcept ZeroDivisionError: print("You cannot divide by zero!")except ValueError: print("Invalid input! Please enter a valid number.")except Exception as e: print(f"An unexpected error occurred: {e}")In this case:
The
ValueErrorwill be caught if the user inputs something that cannot be converted to an integer.The
ZeroDivisionErrorwill be caught if the user inputs0.A general
Exceptionwill catch any other unforeseen errors.
? 4. The else Block
You can use the else block to define code that should execute if no exception occurs:
try: x = 5 / 2except ZeroDivisionError: print("Cannot divide by zero!")else: print(f"The result is: {x}")If no exception is raised in the
tryblock, theelseblock will execute.If an exception occurs, the
elseblock will be skipped.
? 5. The finally Block
The finally block is used to define code that will be executed no matter what, whether an exception occurred or not. It’s often used for cleanup actions like closing files or releasing resources.
try: file = open("file.txt", "r") # Some file operationsexcept FileNotFoundError: print("File not found.")finally: file.close() print("File closed.")The
finallyblock runs regardless of whether an exception was raised.It is typically used for cleanup activities.
? 6. Raising Exceptions
In Python, you can raise exceptions manually using the raise keyword. You can raise built-in exceptions or create your own custom exceptions.
Example: Raising a ValueError:
x = -1if x < 0: raise ValueError("Negative value is not allowed")This will raise a ValueError with the message "Negative value is not allowed."
Example: Creating Custom Exceptions:
class NegativeValueError(Exception): """Custom exception for negative values.""" passx = -5if x < 0: raise NegativeValueError("Custom error: Negative value encountered")Here, we define a custom exception called
NegativeValueErrorthat inherits from Python’s built-inExceptionclass.
? 7. Exception Chaining
In Python, when one exception is caught, another exception can be raised while preserving the original traceback. This is called exception chaining.
try: x = int(input("Enter a number: "))except ValueError as e: print(f"Invalid input: {e}") raise TypeError("Something went wrong with the input handling.") from eHere, if the user enters an invalid value, the
ValueErrorwill be caught, and then aTypeErrorwill be raised while preserving the original exception (ValueError).
? 8. Conclusion
Here’s a summary of the important points about exceptions in Python:
try...except: Used to catch and handle exceptions.else: Executes if no exception occurs in thetryblock.finally: Executes code that should always run (e.g., cleanup) aftertryandexcept.Common exceptions:
ZeroDivisionError,TypeError,ValueError, etc.Custom exceptions: You can create your own exception classes by inheriting from the
Exceptionclass.Raising exceptions: You can use
raiseto throw an exception manually.
Using exceptions properly can make your code more robust and handle errors in a controlled way instead of letting your program crash unexpectedly.
Let me know if you'd like to explore specific exceptions or need more examples! ?