Try / Except statements are great methods for overcoming errors in your code.
The way it works is very simple.
It will be more clear with a few examples.
10 mins
Upper Intermediate
na
Provided by HolyPython.com
If you’d like to see all the Built-in Python Error Types, you can click here.
1) First block starts with try followed by an indentation and statement
2) Second block starts with except followed by an indentation and statement.
1) Don't forget the semicolons (:) after try and except statements.
Here are some Try / Except tips that will make coder’s life easier.
Avoid using BaseException:
except Exception:
format and this will cause your code to overcome most of the exceptions.KeyboardInterrupt
and SystemExit
will still be executed with this method which can be welcome by the programmer as those statements might still be needed to stop or exit the program.You can also record the error type or assign it to a variable to use it in a content or maybe a report or notification.
If you’d like to use the error type in your statement you can do so as well.
Also,
1) type(error)
will give you the class type of the error.
2) (type(error)).__name__
will give the exact name of the type of the error.
See example 5 below.
//
division (floor):**
power: %
modulus:!=
not equal:>=
greater than:<=
lower than:in
in:not in
not in:If a == 0:
Here are some examples that can help you understand Python Operators and their use cases:
You can see free beginner Python lessons regarding data types, data structures, strings, integers etc. here.
>>> a = 5
>>> b = 0
>>> try:
>>> print(a/b)
>>> except ZeroDivisionError:
>>> print(“You can’t divide with 0”)
“You can’t divide with 0“
try/except
where exception occurs and instead of throwing an error program executes whatever you want it to do. >>> a = 5
>>> b = 0
>>> try:
>>> print(a/b)
>>> except:
>>> print(“You can’t divide with 0”)
“You can’t divide with 0“
Without specifying the ZeroDivisionError, it will still catch it with except statement.
>>> a = [1, 3, 5]
>>> try:
>>> a.get()
>>> except:
>>> pass
Instead of specifying the AttributeError we used except and it will jump to the pass statement after the except. Please note that using a naked except is not good Python practice and can cause you trouble in sophisticated applications.
pass statement
, click here. >>> a = “Hello World!”
>>> try:
>>> a + 10
>>> except BaseException as error:
>>> print(‘Exception occurred: {}’.format(error))
lst = [5, 10, 20]
Exception occured: can only concatenate str (not “int”) to str.
lst = [5, 10, 20]
>>> try:
>>> print(lst[5])
>>> except IndexError as error:
>>> print(“Exception is: {}”.format(type(error).__name__))
IndexError
. Next Lesson: Python Classes