Handling and raising exceptions
In Python, you can handle and raise exceptions using the try–except statement. This allows you to catch and handle exceptions that may occur during program execution, so that your program can gracefully recover from them. You can also raise your own exceptions using the raise statement.
Handling Exceptions
Here’s an example of how to use a try–except block to catch and handle an exception:
pythonCopy codetry:
x = 10 / 0
except ZeroDivisionError:
print("Division by zero!")
In the above example, the try block contains the code that may raise an exception, which is dividing the number 10 by zero. The except block specifies the type of exception to catch, which in this case is ZeroDivisionError. If an exception of this type is raised, the except block will execute, which in this case prints a message to the console.
You can also catch multiple exceptions with a single except block:
pythonCopy codetry:
# some code that may raise an exception
except (ExceptionType1, ExceptionType2) as e:
# handle the exception
In the above example, the except block catches two types of exceptions, ExceptionType1 and ExceptionType2, and assigns the exception to the variable e.
You can also use the finally block to specify code that should be executed whether or not an exception is raised:
pythonCopy codetry:
# some code that may raise an exception
except:
# handle the exception
finally:
# code to execute whether or not an exception is raised
In the above example, the finally block specifies code that will always be executed, whether or not an exception is raised.
Raising Exceptions
You can raise your own exceptions using the raise statement:
pythonCopy codeif x < 0:
raise ValueError("x cannot be negative")
In the above example, the raise statement is used to raise a ValueError exception if x is less than zero, along with a message that explains the reason for the exception.
Overall, handling and raising exceptions in Python provide a powerful mechanism for handling errors and exceptional conditions in your code.
Apply for Python Certification!
https://www.vskills.in/certification/certified-python-developer
