In Python, you can use the try
and except
statements to handle exceptions and errors during runtime. Here is an example of using try-except:
main.py175 chars7 lines
In this example, we try to divide 12 by zero, which raises a ZeroDivisionError
exception. We catch this exception with the except
statement and print an error message.
You can also use a bare except
statement to handle all types of exceptions, but this is generally not recommended as it can mask errors that you didn't anticipate. Here is an example of a bare except statement:
main.py179 chars7 lines
In this example, if some_function_that_might_raise_an_exception
raises any kind of exception, we catch it with the bare except
statement and print a generic error message.
However, it's generally better to use specific except
statements to handle specific exceptions, so you can give appropriate feedback to the user and/or log the error in a meaningful way.
gistlibby LogSnag