try except in python

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.py
try:
    # code block that may raise an exception
    result = 12 / 0
except ZeroDivisionError:
    # handler for the specific exception
    print("Error: Division by zero!")
175 chars
7 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.py
try:
    # code that may raise an exception
    result = some_function_that_might_raise_an_exception()
except:
    # handler for all exceptions
    print("Something went wrong!")
179 chars
7 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