Python Exception Handling
What is Exception Handling?
Exception dealing with in Python is a mechanism to cope with errors that could arise at some stage in the execution of a software.
It enables you control unexpected conditions and save you your application from crashing.
Try-Except Block:
Try-besides block is used for exception coping with. It allows you to seize and manage exceptions which can occur all through the execution of a application, preventing the program from crashing due to surprising errors.
try:
# Code that might raise an exception
num = int(input("Enter a number: "))
result = 10 / num
print("Result:", result)
except ZeroDivisionError:
print("Cannot divide by zero.")
except ValueError:
print("Invalid input. Please enter a number.")
except Exception as e:
print("An error occurred:", e)
- The strive block carries the code that might boost an exception.
- The except blocks specify the sort of exception to capture. If an exception takes place, the corresponding except block is completed.
- You can have a couple of except blocks to address special varieties of exceptions.
Handling Multiple Exceptions:
Handling more than one exceptions in Python entails the use of multiple except blocks to catch and cope with unique forms of exceptions which could arise inside the attempt block. This lets in you to provide unique coping with for numerous types of errors.
try:
# Code that might raise an exception
num = int(input("Enter a number: "))
result = 10 / num
print("Result:", result)
except (ZeroDivisionError, ValueError) as e:
print("An error occurred:", e)
except Exception as e:
print("An unexpected error occurred:", e)
Here, the besides block catches either a ZeroDivisionError or a ValueError.
Try-Except-Else Block:
The try-besides-else block is used for exception coping with, much like the try-besides block. However, it includes an additional else block that incorporates code to be completed if no exceptions are raised inside the attempt block.
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Cannot divide by zero.")
except ValueError:
print("Invalid input. Please enter a number.")
else:
print("Result:", result)
The else block is carried out if no exceptions arise in the strive block.
Try-Finally Block:
The try-ultimately block is used for exception managing, and it guarantees that a positive block of code (specific in the finally block) is completed no matter what happens in the preceding attempt block.
try:
file = open("example.txt", "r")
content = file.read()
print(content)
finally:
file.close()
print("File closed.")
The sooner or later block is usually completed, whether an exception occurs or no longer. It's usually used for cleanup operations like closing files.
Custom Exceptions:
You can create custom exceptions by using defining your very own exception lessons. Custom exceptions can help you raise and manage unique errors to your code, imparting greater significant records approximately the nature of the trouble. To create a custom exception, you usually define a new class that inherits from the built-in Exception magnificence or considered one of its subclasses.
class CustomError(Exception):
def __init__(self, message):
self.message = message
try:
raise CustomError("This is a custom error.")
except CustomError as e:
print("Caught a custom error:", e.message)
You can create custom exceptions by way of defining a new class that inherits from the Exception magnificence.
Exception handling is a essential part of writing sturdy and errors-tolerant Python packages. It lets in you to gracefully cope with mistakes, log statistics, and manual the program's conduct in case of sudden situations.