An exception is an error that occurs during the execution of a program. When an exception occurs, the program will stop running and an exception object is created. You can handle exceptions in your code using a try-except block.
Here’s an example of how to handle a ZeroDivisionError exception, which is raised when you try to divide by zero:
try:
x = 1 / 0
except ZeroDivisionError:
print("You cannot divide by zero!")
You can also handle multiple exceptions in the same try-except block using a tuple:
try:
x = 1 / 0
y = 'a' + 1
except (ZeroDivisionError, TypeError):
print("A division by zero or a type error occurred.")
You can raise an exception in your code using the raise
keyword. For example:
raise ValueError("Invalid input")
You can also define your own custom exceptions by creating a new class that inherits from the Exception
class.
class MyCustomException(Exception):
pass
raise MyCustomException("An error occurred")