ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Why You Should Use Try and Except in Python?

Updated on April 13, 2020
Source

The reasons why you should catch errors!

Most of you reasonably asking why do you need it? Why should I add a few more code lines just to catch errors?

Here are the 3 main reasons why you should use these methods:

  1. You will get a more straightforward format of the error.
  2. Your code will not be interrupted.
  3. You can overtake a very specific error in case if you need to.

Now let me explain each of the reasons.

I wrote a simple code for an example. I will use it to show the differences between using the try and except methods and not using them.

First code without the methods

x = 1
b = 2

sum = x + "Hello Alex!"

print(sum)
print("Last line")

Analyzing The Code Output

There are two variables - "x" and "y". Each of them contains a number (Integer). I'm going to take one of the variables and concatenate it with a string "Hello Alex". Most of you know that such action is forbidden and the debugger will throw an error because you cannot add a string to a number.

If you copy and paste this code to your local machine and execute it, there are two things you will notice:

  1. You will get an ugly error output.
  2. Your code will be interrupted. See the last line - it was never printed.

Check the output below.

First code without the methods - error output

G:\Python3\python.exe "C:/Users/reinc/PycharmProjects/test/Try Except/try_except"
Traceback (most recent call last):
  File "C:/XXX/try_except", line 5, in <module>
    sum = x + "Hello Alex!"
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Process finished with exit code 1

Lets add Try and Except to the code

The next snippet of a code will examine the process of the code while having the try and except methods.

The code with the methods

x = 1
b = 2
try:
    sum = x + "Hello Alex!"
except Exception as e:
    print(e)

print(sum)
print("Last line")

Discussion about before and after using the methods

Please notice below that two things happened here, which are the same actions but in a better code design:

  1. We received a shorter and more readable error output.
  2. Our code was note interrupted. Did you notice that the last line was printed?

I've been using try and except many times. I can guarantee you that once you will get used to using it, your code will look more professional, it will have a better performance as it will never get interrupted.

Also notice that in that very specific example, I used a basic error code. In many cases when you will use more complicated tools such as "requests", you might face lots of different possible errors (and not only one error type), then you might be interested to get more accurate error outputs.

Imagine a situation at work - your boss is asking you to write a code that connects to a specific URL, logging in and that's it. Simple, isn't it?

In addition, your boss wants to know what was the reason for the connection error and he wants to receive this error immediately once it occurred.

Will you run that code manually? Copy and paste it, then send it to your boss manually via email?

The best practice would be to wrap the connectivity code part with try and except method and right after it to add a few more lines which will send the email with the exception right yo your boss.

Please remember, the code will not be interrupted with try and except methods.

At the end of the day, your boss will be satisfied with you completing the task, he will be delighted with receiving the exception via email and you will be happy that you completed your boss's task and provided a solution for him.


The code with the methods - error output

G:\Python3\python.exe "C:/Users/reinc/PycharmProjects/test/Try Except/try_except"
unsupported operand type(s) for +: 'int' and 'str'
<built-in function sum>
Last line

Process finished with exit code 0

My Tutorial For Beginners

My Tutorial For Advanced Level

Conclusions

A programmer must know how to use try and except methods. This is not only about Python, this is relevant for any type of programming language that allows the programmer to catch errors.

Last tip, if you ever used the "logging" module, you should try to combine it with the try and except methods. It's a great combination of writing a log file with specific points of failure inside of the code while it is running.

One more important thing, if you work in a big corporate with many other developers, you should remember the others will see your code, they will judge your work, this is your developer "stamp" of who and how the code was written.


This content is accurate and true to the best of the author’s knowledge and is not meant to substitute for formal and individualized advice from a qualified professional.

© 2020 Alex Ledovski

working

This website uses cookies

As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://corp.maven.io/privacy-policy

Show Details
Necessary
HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
LoginThis is necessary to sign in to the HubPages Service.
Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
AkismetThis is used to detect comment spam. (Privacy Policy)
HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
Features
Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
MavenThis supports the Maven widget and search functionality. (Privacy Policy)
Marketing
Google AdSenseThis is an ad network. (Privacy Policy)
Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
Index ExchangeThis is an ad network. (Privacy Policy)
SovrnThis is an ad network. (Privacy Policy)
Facebook AdsThis is an ad network. (Privacy Policy)
Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
AppNexusThis is an ad network. (Privacy Policy)
OpenxThis is an ad network. (Privacy Policy)
Rubicon ProjectThis is an ad network. (Privacy Policy)
TripleLiftThis is an ad network. (Privacy Policy)
Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
Statistics
Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
ClickscoThis is a data management platform studying reader behavior (Privacy Policy)