Python

Try-Except Statements in Python

“When writing code in Python, especially if it’s a bit more complicated, you’re more than likely to encounter errors. So the way of writing good code is to handle these errors skillfully. We need to ensure that we can smoothly pipe these errors into another route. And so, for this purpose, in Python, the try-except statement was created. The try-except statement consists of a try block and one or more except blocks. In this tutorial, we’ll be learning about the try-except statement.”

Try-Except Statement

The Try-Except statement looks something like this:

try:

Code

except ExceptionName:

Code

So, we have the try statement, and then code is placed there; this is the main code you wish to execute. Then there is the except statement with another set of codes, but this code is meant to deal with the exception. Python will attempt to first and foremost execute all the code within the try statement. When there’s no error, then everything goes fine, and the except statement is simply passed over (skipped). If, on the other hand, an exception occurs, then Python will check to see if it matches the ExceptionName in the except statement. If it does match, then it will begin executing the except statement’s code.

Example #1

main.py

try:

y=(2/3)

print(y)

except ZeroDivisionError as error:

print("Error: %s" % error)

print("This statement is outside the try-except clause.")

Output:

0.6666666666666666

This statement is outside the try-except clause.

Process finished with exit code 0

So here, we have a try-except statement and then a little bit of code outside the try-except block. Because we’re dividing 2 by 3 and that it gives us a valid number, it will execute the try statement and then bypass the except statement – because there’s no ZeroDivisionError. Once it bypasses the except statement, it continues with the rest of the program and ends smoothly. The point of this example is to show that the except statement can be bypassed.

Example #2

main.py

try:

y= (2/0)

print(y)

except ZeroDivisionError as error:

print("Error: %s" % error)

Output:

Error: division by zero

Process finished with exit code 0

In this case, in the try block, we’re trying to divide 2 by 0 and assign the value to y. As you might or might not know, you simply cannot divide by 0, so there’s a little problem here. Since we want to be skillful in dealing with errors, we have decided to write an except block with the exception name of ZeroDivisionError. What this does is to catch ZeroDivisionError or, in other words, division by zero error and print out the error. So what do we get? A statement saying that you simply cannot divide by zero. But the point is that our program didn’t crash! It instead pointed out the flaw.

Example #3

main.py

try:

file = "file.txt"

f=open(file, 'r')

print(f.read())

except ZeroDivisionError as error:

print(error)

except SyntaxError as serror:

print(serror)

except FileNotFoundError as ferror:

print(ferror)

Output:

[Errno 2] No such file or directory: 'file.txt'

Process finished with exit code 0

The point of this example is simple – you can write out as many exceptions as you want. If you think there could be a FileNotFoundError, you add it to the list of errors. This will mean that when Python tries to execute the try block, it doesn’t find the file, so it exits the try statement and searches through the except statements to see if any of them match the error raised. Since the last one matches, it will print out the ferror or the FileNotFoundError.

Example #4

In this case, we’re going to look at an example that takes this format:

try:

Code set 1

Code set 2

except ExceptionName1:

Code set 3

except ExceptionName2:

Code set 4

except ExceptionName3:

Code set 5
main.py

try:

file = "file.txt"

f=open(file, 'r')

print(f.read())

y=(2/0)

print(y)

except ZeroDivisionError as error:

print(error)

except SyntaxError as serror:

print(serror)

except FileNotFoundError as ferror:

print(ferror)

Output:

[Errno 2] No such file or directory: 'file.txt'

Process finished with exit code 0

In this particular example, we have two mistakes – a FileNotFoundError and a ZeroDivisionError. But notice how the first error is the FileNotFoundError. So what does Python do? It starts reading the code, the try statement, and encounters the FileNotFoundError, so it exits the try statement and starts scanning through the various except statements, and it finds the FileNotFoundError except for statement and thereby executes the code within it. Here, the second mistake is omitted, and we do not get a ZeroDivisionError.

Example #5

main.py
try:

x='9'

if x > 6:

print(x/6)

except ZeroDivisionError as error:

print(error)

except:

print("Some other error")

Output:

Some other error

Process finished with exit code 0

So in this example, there was a TypeError because you cannot use > between a string and an integer. So, the try block is attempted, and when it faces the type error, it goes straight to the “general” except clause and executes that. In other words, if you want to catch errors and you don’t know their names, you can leave the ExceptionName part blank.

The point of this example is that you can use the except statement without naming an error, and it should, in theory, catch any error thrown, but it’s not advised! In other words, to just use except without an Exception Name is not really advised.

Conclusion

The try-except statement is a blessing to all programmers who use Python. The try-except statement consists of two or more blocks. The first block is always the try statement block which is stuffed with code. After which, you can add one or more except blocks in order to catch very specific errors. Usually, you have to also assign a name to the except statement (ex: except ZeroDivisionError); however, if you really don’t know what kind of errors you’ll be encountering, you can leave it blank (ex: except). Either way, the best of all programmers will know not to make mistakes and therefore tend to utilize fewer except blocks but to each their taste. So use the try-except statement wisely. Don’t forget that programming implies skill.

Happy Coding!

About the author

Kalyani Rajalingham

I'm a linux and code lover.