One annoying thing about programming is the wide range of errors that crop up
due to (for example) just a tiny typo. Luckily, Python offers various error
handling tools, one of which is the try-except block.
The try block
The try block allows you to test a block of code for errors. In
other words, the piece of code under try is checked to look for
any errors in it.
Like seen commonly in Python, indentations are used to specify which line is inside the block.
For example-
x = 10
try:
print(x)
except:
print("An error occured.")
Note: Thetryblock cannot be used withoutexcept.
The except block
Generally, if an error is encountered, Python stops execution immediately and
displays the error with it's line number. However, if an error occurs within
the try block, the code inside the except block is
executed immediately.
For example-
try:
print(a)
except:
print("An error occured.")
The output-
An error occured.
A specific type of error can also be specified along with except.
Some common errors in Python are SyntaxError, ValueError, NameError, etc.
(there are a lot more). If a specific error is specified, the
except block will execute only if that type of error is
encountered. If any other error occurs, the program will terminate as usual.
For example-
try:
print(x)
except NameError:
print("An error occured.")
try:
if 5 > 3:
print("Hi")
except NameError:
print("An error occured.")
The outputs-
An error occured.
File "/Users/username/folder1/folder2/file.py", line 3
print("Hi")
^
IndentationError: expected an indented block after 'if' statement on line 2
In the second case, we encounter an IndentationError. This type of error is
not mentioned with the except. Hence, it's presence does not
trigger the except block.
Note: You can define as many except blocks as you would
like, in case you want different outputs for different types of errors.
Else blocks
You can also add an else block after the try-except.
The content of this block will get executed only if no errors are detected. If
an error is detected,
For example-
x = "Hi!"
try:
print(x)
except SyntaxError:
print("SyntaxError detected.")
else:
print("There seems to be no error.")
The output
Hi!
There seems to be no error.
The finally block
The finally block can be added at the last, after the try, all
the except blocks and (if present) the else. The
code inside this block is executed after the try-except, regardless of whether
an error was detected or not.
For example-
x = "Hi!"
try:
print(x)
except SyntaxError:
print("SyntaxError detected.")
else:
print("There seems to be no error.")
finally:
print("This line is always printed.")
The output-
Hi!
There seems to be no error.
This line is always printed.
That is all for this post on try-except. Any questions or suggestions can be conveyed through the comments.
Happy coding,
Aarav Iyer