In Python, exceptions are errors that occur during the execution of a program. Handling exceptions is important because it can prevent the program from crashing and make it more robust.
To handle exceptions in Python, you can use a try-except block. The code inside the try block is executed first, and if an exception is raised, it is caught by the except block.
Here's an example:
main.py219 chars9 lines
In this example, we're using the try
block to get user input and perform a division. If the user enters 0
, a ZeroDivisionError
will be raised. If the user enters a non-integer value, a ValueError
will be raised.
The except
blocks catch these exceptions and print a user-friendly error message.
You can also raise
exceptions in Python. This is useful if you want to create custom exceptions for your own code.
Here's an example:
main.py234 chars8 lines
In this example, we're defining a function that calculates a person's age based on their birth year. If the user enters a negative year, we're raising a ValueError
with a custom error message.
Overall, handling and raising exceptions is an important part of writing robust code in Python.
gistlibby LogSnag